VC ++ 6项目迁移到VC ++ 2008时模板化的类编译错误

时间:2013-05-03 16:41:29

标签: c++ templates

我有一个类,见下文,在VC ++ v6项目中编译得很好,但是当迁移到VS2008时,我遇到了编译错误(如下面的代码所示)。

template<class T> class my_enum_test 
{
public:
    enum EState { STARTING, RUNNING, STOPPING, STOPPED, IDLE};

    my_enum_test(T* object) : object_(object), state_(IDLE) {}

    my_enum_test<T>::EState get_state() const;

private:
    EState state;      // execution state
    T* object_;
};


template <class T>
my_enum_test<T>::EState my_enum_test<T>::get_state(
    ) const
{
    return state;
}


int main() {

    my_enum_test<int> my_test;
    my_enum_test<int>::EState the_state = my_test.get_state();

    return 0;
}

错误:

Compiling...
main.cpp
main.cpp(9) : warning C4346: 'my_enum_test::EState' : dependent name is not a type
        prefix with 'typename' to indicate a type
        main.cpp(14) : see reference to class template instantiation 'my_enum_test'    being compiled
main.cpp(9) : error C2146: syntax error : missing ';' before identifier 'get_state'
main.cpp(9) : error C2875: using-declaration causes a multiple declaration of 'EState'
main.cpp(9) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
main.cpp(9) : warning C4183: 'get_state': missing return type; assumed to be a member function returning 'int'
main.cpp(18) : warning C4346: 'my_enum_test::EState' : dependent name is not a type
        prefix with 'typename' to indicate a type
main.cpp(18) : error C2143: syntax error : missing ';' before 'my_enum_test::get_state'
main.cpp(18) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
main.cpp(18) : fatal error C1903: unable to recover from previous error(s); stopping compilation
Results

忽略类没有做任何事情的事实,我该如何解决编译问题?

1 个答案:

答案 0 :(得分:1)

由于您具有合格的依赖类型名称(EState),因此您需要使用typename消除歧义器:

    template <class T>
    typename my_enum_test<T>::EState my_enum_test<T>::get_state(
//  ^^^^^^^^
        ) const
    {
        return state;
    }

这样编译器就会知道EState是类型的名称,而不是静态成员变量的名称。