[英]c++ template function argument deduce and function resolution
今天,我只想提出一個關於C ++ 11中C ++模板函數自變量推斷和模板函數重載解析的問題(我正在使用vs2010 sp1)。 我定義了兩個模板函數,如下所示:
功能#1:
template <class T>
void func(const T& arg)
{
cout << "void func(const T&)" <<endl;
}
功能2:
template <class T>
void func(T&& arg)
{
cout << "void func(T&&)" <<endl;
}
現在考慮以下代碼:
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);}
}
我只想知道在這些情況下指導函數重載解析的背后規則。
我不同意以下兩個答案,我認為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”);
在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和字符串文字。
請注意,過載#2與T&和T &&完全匹配。 因此,兩個重載都可以綁定到rvalue和lvalue。 在您的示例中,重載區分主要在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"
是const char(&)[5]
-第一個重載中const T&
精確匹配。 (&)
表示這是參考。
//Here function#2 is selected in which T is deduced as char(&)[5]
{char array[] = “feng”; func(array);}
數組-是char(&)[5]
-第二次重載中T&
完全匹配
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.