VC ++功能模板实例化错误C2664使用不同的枚举参数时 [英] VC++ Function Template Instantiation Error C2664 When Using Different Enum Arguments

查看:385
本文介绍了VC ++功能模板实例化错误C2664使用不同的枚举参数时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  // cpptests.cpp:控制台应用程序。 
//

#includestdafx.h
#include< iostream>
using namespace std;
template< typename U1>
int insert_unit01(const U1& u1){
return 0;
}
枚举{A1,A2};
枚举{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):错误C2664:'insert_unit01':无法转换
参数1从''到'const&'原因:无法从'
转换为'const'转换为枚举类型需要显式转换
(static_cast,C风格的转换或函数式转换)$问题是,我使用另一个枚举器实例化相同的模板函数 B1 / code>( A1 之后)。

我是C ++模板的新用户。为什么会出现这样的错误?

在执行参数扣除时是否有与枚举相关的特定规则?是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};


The following codes produces compilation error in 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)

The problem is that I was instantiating the same template function using another enumerator B1 (after A1).
I am new to C++template. Why is there such an error?
Are there any specific rules related to enum when doing argument deduction? Is it VC++2010 specific?

EDIT: Note that this compiles correctly (without calling the template function a second time using B1)

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

So why it didn't instantiate a second function for insert_unit01(B1), but instead produced a compilation error?

解决方案

Using anonymous enums as template arguments is only allowed since C++11, so either build in C++11 mode, or don't use anonymous enums as template arguments :

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

这篇关于VC ++功能模板实例化错误C2664使用不同的枚举参数时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆