c++;模板函数参数推导与函数解析 今天我想提出一个关于C++模板函数参数推导和模板函数重载解析的C++ 11的问题(我使用VS201SP1)。 我定义了两个模板函数,如下所示:
功能#1: 我只想知道在这些场景下指导函数重载解决方案的规则 我不同意下面的两个答案。我认为const int示例与literal string示例不同。我可以稍微修改一下#函数1,看看到底推导出了什么类型c++;模板函数参数推导与函数解析 今天我想提出一个关于C++模板函数参数推导和模板函数重载解析的C++ 11的问题(我使用VS201SP1)。 我定义了两个模板函数,如下所示:,c++,function,templates,c++11,resolution,C++,Function,Templates,C++11,Resolution,功能#1: 我只想知道在这些场景下指导函数重载解决方案的规则 我不同意下面的两个答案。我认为const int示例与literal string示例不同。我可以稍微修改一下#函数1,看看到底推导出了什么类型 template <class T> void func(const T& arg) { T local; local = 0; cout << "void func(const T&)" <<endl; }
template <class T>
void func(const T& arg)
{
T local;
local = 0;
cout << "void func(const T&)" <<endl;
}
//the compiler compiles the code happily
//and it justify that the T is deduced as int type
const int a = 0;
func(a);
template <class T>
void func(const T& arg)
{
T local;
Local[0] = ‘a’;
cout << "void func(const T&)" <<endl;
}
//The compiler complains that “error C2734: 'local' : const object must be
//initialized if not extern
//see reference to function template instantiation
//'void func<const char[5]>(T (&))' being compiled
// with
// [
// T=const char [5]
// ]
Func(“feng”);
模板
无效函数(常量T和参数)
{
T局部;
局部=0;
cout这里的诀窍是const
。F1和F2都可以接受任何类型的值,但F2通常是更好的匹配,因为它是完美的转发。因此,除非该值是const
左值,否则F2是最佳匹配。然而,当左值是const
时,F1是更好的匹配。这就是为什么它是首选的const int和字符串literal。请注意,重载#2与T&和T&&完全匹配。因此这两个重载都可以绑定到右值和左值。在您的示例中,重载微分主要是在constness上完成的
//Function #2 is selected... why?
//Why not function #1 or ambiguous...
{func(0);}
0
是int&
-与T&
//But here function #1 is selected.
//I know the literal string “feng” is lvalue expression and
//T is deduced as “const char[5]”. The const modifier is part
//of the T type not the const modifier in “const T&” declaration.
{func(“feng”)}
文本“feng”
是常量字符(&)[5]
-与第一次重载中的常量T&
完全匹配。(&)
表示这是一个引用
//Here function#2 is selected in which T is deduced as char(&)[5]
{char array[] = “feng”; func(array);}
数组-ischar(&)[5]
-与第二个重载中的T&
完全匹配我修改了你的问题,使其更具可读性,但我删除了一些我不理解的部分。请通读新版本,并重新添加任何你认为重要的内容(我遗漏了)@Leonid:你在抽什么?你想把一个非常量左值推导出为右值引用?那太疯狂了。T被推导出int&
是完全正确的。@DeadMG-你是对的,它被推导出为int&
。我已经从func()
打印的内容中剪切和粘贴了,而没有考虑它。我期望{func>(0);}
取常量T&
版本。为什么选择T&&
呢?在这种情况下,T是const int
。不,0
是int&
标准是这样说的。我不同意你的观点。我有补充证据。
//Function #2 is selected... why?
//Why not function #1 or ambiguous...
{func(0);}
//But here function #1 is selected.
//I know the literal string “feng” is lvalue expression and
//T is deduced as “const char[5]”. The const modifier is part
//of the T type not the const modifier in “const T&” declaration.
{func(“feng”)}
//Here function#2 is selected in which T is deduced as char(&)[5]
{char array[] = “feng”; func(array);}