C ++ 11模板错误消息:“无法调用无对象的成员函数”

时间:2013-03-10 21:50:44

标签: c++ templates c++11

以下是生成用于添加N个向量的表达式模板的代码,但是目前我只想添加两个向量。

template < typename Operation, typename Va>
struct VectorExpression < Operation, Va >
{
    friend Va;
    typedef VectorExpression< Operation, Va> This;
    const Operation& op;
    const Va& vector;

    inline VectorExpression ( Operation oper, const Va& first) : op(oper), vector(first) {};

    inline auto size() const ->decltype( vector.size() ) {
        return vector.size();
    };

    inline auto operator[]( size_t i ) const 
        ->decltype( vector[i] ) {
        return vector[i];
        };
};

template < typename Operation, typename Va, typename ... Vs >
struct VectorExpression <Operation, Va, Vs...> : protected VectorExpression< Operation, Vs...>
{
    friend Va;
    typedef VectorExpression< Operation, Va, Vs...> This;
    typedef VectorExpression< Operation, Vs... > Base;
    const Operation op;
    const Va& vector;

    inline VectorExpression ( Operation oper, const Va& first, const Vs&... vs ) : VectorExpression< Operation, Vs...>(oper, vs...), op(oper), vector(first) {};

    inline auto size() const ->decltype( vector.size() ) {
        return vector.size();
    };

    inline auto operator[]( size_t i ) const //This line is where the error says it is happening
        ->decltype( op( vector[i], Base::operator[](i) ) ) {
        return op( vector[i], Base::operator[](i) );
        };
};

不幸的是,当我尝试编译前面的内容时,我收到以下错误消息:

error: cannot call member function 'decltype (((const VectorExpression<Operation, Va>*)this)->VectorExpression<Operation, Va>::vector[i]) 
    VectorExpression<Operation, Va>::operator[](size_t) const 
    [with 
        Operation = adder<std::complex<double>, double>; 
        Va = Vector<double, false>; 
        decltype (((const VectorExpression<Operation, Va>*)this)->VectorExpression<Operation, Va>::vector[i]) = const double&; size_t = long unsigned int]'  without object

我不确定问题出在哪里。它似乎是operator[]的一个相当简单的递归定义,在当前对象中添加了带有所有基类向量的向量。

有什么想法吗?我不相信代码的其余部分是相关的[编辑:但是可以找到标题here,并且可以找到测试“main”here,但是如果您希望看到它,让我知道。另外,在C ++ 11中是否有办法在调试此类问题的位置打印出类型?

1 个答案:

答案 0 :(得分:5)

您不能在Base::operator[](i)中执行decltype,因为它不在成员函数的正文中;你必须做this->Base::operator[](i)