对模板化基类的模板化成员的调用失败

call to templated member of templated base class fails

本文关键字:失败 调用 基类 成员      更新时间:2023-10-16

我有一个问题,这里似乎已经讨论过了:CPP模板成员函数专业化

但是this->template的解决方案与我的示例不兼容。

以下代码失败:

错误:类型"<未解析的重载函数类型>'和'int'到二进制"operator<"

带有gcc 4.8.1

class Base { public: virtual int Do(){return 0;} };
class State1: public Base {};
class State2: public Base {};
template <typename ... T> class SM;
template <class StateBase, class HeadState, class ... States >
class SM<StateBase, HeadState, States...> : public SM< StateBase, States...>
{
    protected:
        HeadState headState;
        template<int cnt> StateBase* GetNextState ( unsigned int index ) { return headState; }
};  
template <class StateBase, class HeadState>
class SM< StateBase, HeadState>
{
    protected:
        HeadState headState;
        template<int cnt> StateBase* GetNextState ( unsigned int index ) { return headState; }
};  
template <class StateBase, class ... States >
class TopSM: public SM< StateBase, States...>
{
    public:
        void DoIt()
        {
            // following code fails with 
            // error: invalid operands of types '<unresolved overloaded function type>' and 'int' to binary 'operator<'
            int nextState = this->template SM< StateBase, States...>::GetNextState <1>( 1 );
        }
};  
TopSM<Base, State1, State2> sm;
int main()
{
    sm.DoIt();
    return 0;
}

GetNextState之前需要另一个template。如果标识符后面有模板参数,之前有.->::,并且它是依赖于模板参数的某个成员,则需要有template关键字来消除小于号的歧义。

int nextState = this->template SM< StateBase, States...>::template GetNextState <1>( 1 );

差不多了,你需要另一个template

int nextState = this->template SM< StateBase, States...>::template GetNextState <1>( 1 );
                                                          ~~~~~~~~

问题是,由于GetNextState来自模板参数,它不知道它是静态变量、函数、模板函数还是其他什么。解析器需要继续,因此它假设它不是一个模板函数,因此<被解析为小于运算符,而不是模板参数列表的开头。从那里,解析器会变得混乱,您会得到关于>的无效操作数的错误。

相关文章: