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

时间:2014-07-04 09:19:00

标签: 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)实例化第二个函数,而是产生了编译错误?

1 个答案:

答案 0 :(得分:1)

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

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