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

时间:2013-08-07 08:34:24

标签: c++ templates c++11

我有一个问题似乎已经在这里讨论过了: CPP templated member function specialization

this->template的解决方案与我的示例无关。

以下代码失败:

error: invalid operands of types '<unresolved overloaded function type>' and 'int'
       to binary '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;
}

2 个答案:

答案 0 :(得分:5)

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

template

答案 1 :(得分:2)

几乎在那里,你需要另一个template

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

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