【问题标题】:C++: enum type as template argument - global scopeC++:枚举类型作为模板参数 - 全局范围
【发布时间】:2014-02-07 15:47:42
【问题描述】:

我有这种情况:

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 变量之前编写上述行,则会出现错误

没有匹配的函数调用‘foo(main()::myEnumType&)’ 候选是:模板 int foo(const myEnumType&)

为什么???如何在主目录中进行类型定义? 谢谢!

【问题讨论】:

  • 使用本地类型作为模板类型参数是 C++11 的一个特性。确保您的编译器支持它并且您使用的是 C++11 模式(如果可能)。 Code is working, live example
  • (顺便说一句,我不知道你为什么不应该在 C++ 中只使用 enum myEnumType {AAA, BBB};
  • 但是为什么我改为写'typedef int myEnumType;'那么如果我将它写在main()中也可以吗? 'int' 和 'enum' 有什么区别?
  • int 绝不是本地类型。局部类型是在函数内部定义的类型。 typedefs 非常透明,所以它(看起来)不在乎你是使用 typedef 还是引用的类型。

标签: c++ function templates enums global


【解决方案1】:

您使用的是 C++11 之前的 C++,它不允许在模板参数中使用“本地”类型。幸运的是,此功能已在 C++11 中引入。作为you can see,它在带有-std=c++11 标志的情况下编译得很好,而it fails 没有。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多