c++ - 使用不同的枚举参数时,VC++ 函数模板实例化错误 C2664

标签 c++ templates

以下代码在 VC++2010 中产生编译错误:

// cpptests.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;
template <typename U1>
int insert_unit01(const U1& u1) {
    return 0;
}
enum {A1,A2 };
enum {B1,B2 };

int _tmain(int argc, _TCHAR* argv[])
{
    cout << insert_unit01(A1) << endl;
    cout << insert_unit01(B1) << endl;
    return 0;
}



C:\work\cpptests.cpp(23): error C2664: 'insert_unit01' : cannot convert 
parameter 1 from '' to 'const &' Reason: cannot convert from '' 
to 'const 'Conversion to enumeration type requires an explicit cast 
(static_cast, C-style cast or function-style cast)

问题是我正在使用另一个枚举器 B1(在 A1 之后)实例化相同的模板函数。
我是 C++ 模板的新手。为什么会出现这样的错误?
enum 进行参数推导时有没有相关的特定规则?它是 VC++2010 特定的吗?

编辑:请注意,此编译正确(无需使用 B1 再次调用模板函数)

int _tmain(int argc, _TCHAR* argv[])
{
    cout << insert_unit01(A1) << endl;
    return 0;
}

那么为什么它没有为 insert_unit01(B1) 实例化第二个函数,而是产生了编译错误?

最佳答案

仅自 C++11 起才允许使用匿名枚举作为模板参数,因此要么以 C++11 模式构建,要么不要使用匿名枚举作为模板参数:

enum MyEnumA {A1,A2 };
enum MyEnumB {B1,B2 };

关于c++ - 使用不同的枚举参数时,VC++ 函数模板实例化错误 C2664,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24570840/

相关文章:

c++ - 表观包封

android - QT-creator 2.8 无法部署到 android,ant clean 调试失败

c++ - 为什么内联模板特化有帮助,我应该这样做吗?

C++函数模板问题

C++ - 模板 is_Pointer 似乎失败的奇怪情况

templates - 博客预告片节点的节点模板

c++ - 使用 Code::Blocks 调试时提供程序参数

c++ - 如何在 visual studio(c++) 中将文字中文字符串分配给 wchar_t*?

c++ - 使用 std::function 包装非静态成员函数指针

c++ - std::is_same - 从 integral_constant 继承函数的用例