以下代码在 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/