2014-02-07 62 views
3

我有一个这样的情况:C++:枚举类型作为模板参数 - 全球范围内

template<typename myEnumType> 
int foo(const myEnumType & shortest_paths_algorithm) 
{ 
    ... 
} 

int main() 
{ 
    myEnumType enum_type_istance; 
    int a = foo(enum_type_istance) 
} 

,如果我在函数声明之前的一切声明

typedef enum {AAA, BBB} myEnumType; 

是确定的。虽然,如果我写创建enum_type_istance变量之前,上面的线,得到错误

没有匹配函数调用“富(主():: myEnumType &)” 候选人是:模板INT FOO(常量myEnumType &)

为什么?我怎么能在main中定义type? 谢谢!

+2

使用本地类型作为模板类型参数是一个C++ 11功能。确保你的编译器支持它,并且你正在使用C++ 11模式(如果可能的话)。 [代码正在工作,现场示例](http://coliru.stacked-crooked.com/a/beea71d10a306b08) – dyp

+1

(顺便说一句,我知道没有理由你不应该只使用'enum myEnumType {AAA,BBB};'在C++中) – dyp

+0

但为什么如果我写'typedef int myEnumType;'那么它也适用,如果我写在main()中? 'int'和'enum'有什么区别? – user1403546

回答

4

您在C++ 11之前使用C++,它不允许在模板参数中使用“本地”类型。幸运的是,这个特性已经在C++ 11中引入了。由于you can see它与-std=c++11标志编译得很好,而it fails没有。