You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Eigen::Tensor链式操作后调用.sum()无法提取标量的编译错误求助

Eigen Tensor库sum()无法提取标量的编译错误解决方法

问题代码

#include <iostream>
#include <unsupported/Eigen/CXX11/Tensor>

int main() {
    using namespace Eigen;
    // 填充张量数据
    Tensor<std::complex<double>, 4> xi1st(3, 3, 3, 3);
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            for (int k = 0; k < 3; ++k) {
                for (int l = 0; l < 3; ++l) {
                    xi1st(i, j, k, l) = std::complex<double>(i + j + k + l, i - j + k - l);
                }
            }
        }
    }
    // 示例索引
    int i = 1, j = 1, k = 1;
    // 尝试从嵌套操作中提取求和结果
    auto xi1st_slice = xi1st.slice(Eigen::array<Index, 4>({0, i, j, k}), Eigen::array<Index, 4>({3, 1, 1, 1}));
    auto xi1st_conj = xi1st_slice.conjugate();
    std::complex<double> xi1st_sum = xi1st_conj.sum();
    std::cout << "xi1st_sum: " << xi1st_sum << std::endl;
    return 0;
}

编译错误信息

<source>: In function 'int main()':
<source>:31:52: error: conversion from 'const Eigen::TensorReductionOp<Eigen::internal::SumReducer<std::complex<double> >, const Eigen::DimensionList<long int, 4>, const Eigen::TensorCwiseUnaryOp<Eigen::internal::scalar_conjugate_op<std::complex<double> >, const Eigen::TensorSlicingOp<const std::array<long int, 4>, const std::array<long int, 4>, Eigen::Tensor<std::complex<double>, 4> > >, Eigen::MakePointer>' to non-scalar type 'std::complex<double>' requested
   31 |     std::complex<double> xi1st_sum = xi1st_conj.sum();
      |                                      ~~~~~~~~~~~~~~^~
Compiler returned: 1

问题原因与解决方法

Eigen的Tensor模块采用**延迟求值(lazy evaluation)**机制,slice、conjugate、sum这类操作不会立即计算结果,而是返回一个代表运算逻辑的表达式对象。sum()返回的TensorReductionOp本质是一个0维张量表达式,无法直接隐式转换为std::complex<double>,必须显式触发求值并提取标量。

两种可行的解决方式:

  1. 调用()运算符直接提取0维张量的唯一元素:
    修改求和赋值行:

    std::complex<double> xi1st_sum = xi1st_conj.sum()();
    

    链式调用写法:

    std::complex<double> xi1st_sum = xi1st
        .slice(Eigen::array<Index, 4>({0, i, j, k}), Eigen::array<Index, 4>({3, 1, 1, 1}))
        .conjugate()
        .sum()();
    
  2. 使用eval()显式触发求值:
    eval()会先计算出完整的0维张量对象,该对象可隐式转换为对应标量类型:

    std::complex<double> xi1st_sum = xi1st_conj.sum().eval();
    

    链式调用写法:

    std::complex<double> xi1st_sum = xi1st
        .slice(Eigen::array<Index, 4>({0, i, j, k}), Eigen::array<Index, 4>({3, 1, 1, 1}))
        .conjugate()
        .sum()
        .eval();
    

两种方法都能正确获取求和后的标量值,解决编译错误。

内容的提问来源于stack exchange,提问作者Yes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 09:23:09