오늘 저는 C++ 템플릿 함수 인수 추론 및 템플릿 함수 오버로드 해결 방법을 C++ 11 (vs2010 sp1을 사용하고 있습니다)에서 제기하고 싶습니다. 나는 다음과 같이 두 가지 템플릿 함수 정의 :C++ 템플릿 함수 인수 추론 및 함수 해결
기능 # 1 :
template <class T>
void func(const T& arg)
{
cout << "void func(const T&)" <<endl;
}
기능 # 2 :
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);}
}
I :
template <class T>
void func(T&& arg)
{
cout << "void func(T&&)" <<endl;
}
이제 다음 코드를 고려를 이 시나리오에서 함수 오버로딩의 지침 뒤에있는 규칙을 알고 싶을뿐입니다. 이오스.
아래의 두 답변에 동의하지 않습니다. const int 예제가 리터럴 문자열 예제와 다릅니다. 나는 CONST의 INT의 예에서 지구
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”);
에서 유추 된 형식이 무엇을 볼 수 #function 1을 약간 수정할 수 있으며, "CONST T &"선언에서 const를 수정은 CONST의 INT의 "를 const와"를 먹고 ; 리터럴 문자열 예제에서는 "const T &"선언에서 const 수정자가 어디로 가는지 알지 못합니다. & const를 선언하는 것은 의미가 없습니다 (int * const를 선언하는 것은 의미가 있습니다).
. 새 버전을 읽고 중요하다고 생각되는 항목을 다시 추가하십시오 (그리고 놓친 내용). – Mankarse
@ 레오 니드 : 당신은 무엇을 피우고 있습니까? * const가 아닌 lvalue *가 rvalue reference가되도록 추론 하시겠습니까? 그것은 광기입니다. 'int '로 추론 된 T는 완벽하게 정확합니다. – Puppy
@DeadMG - 정확합니다. 'int'로 추론됩니다. 나는 그것에 대해 생각하지 않고'func()'에 의해 인쇄 된 것을 잘라내어 붙여 넣었다. –