cha*_*eng 4 c++ templates resolution function c++11
今天我只想提出一个关于C++模板函数参数推导和模板函数重载决议的问题在c ++ 11中(我使用的是vs2010 sp1).我已经定义了两个模板函数,如下所示:
功能#1:
template <class T>
void func(const T& arg)
{
cout << "void func(const T&)" <<endl;
}
Run Code Online (Sandbox Code Playgroud)
功能#2:
template <class T>
void func(T&& arg)
{
cout << "void func(T&&)" <<endl;
}
Run Code Online (Sandbox Code Playgroud)
现在考虑以下代码:
int main() {
//I understand these first two examples:
//function #2 is selected, with T deduced as int&
//If I comment out function #2, function#1 is selected with
//T deduced as int
{int a = 0; func(a);}
//function #1 is selected, with T is deduced as int.
//If I comment out function #1, function #2 is selected,
//with T deduced as const int&.
{const int a = 0; func(a);}
//I don't understand the following examples:
//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);}
}
Run Code Online (Sandbox Code Playgroud)
我只想知道在这些场景下引导功能重载解决方案背后的规则.
我不同意下面的两个答案.我认为const int示例与文字字符串示例不同.我可以稍微修改#function 1以查看地球上推断出的类型
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”);
Run Code Online (Sandbox Code Playgroud)
在const int示例中,"const T&"声明中的const修饰符吃掉了const int的"constness"; 而在文字字符串示例中,我不知道"const T&"声明中的const修饰符在哪里.声明一些像int和const是没有意义的(但声明int*const是有意义的)
这里的诀窍是const
.F1和F2都可以接受任何类型的任何值,但F2通常是更好的匹配,因为它是完美的转发.因此,除非该值是const
左值,否则F2是最佳匹配.但是,当左值是const
,F1是更好的匹配.这就是为什么它首选const int和字符串文字.