gpt4 book ai didi

c++模板函数参数推导和函数解析

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:38:11 27 4
gpt4 key购买 nike

今天我只是想提出一个关于C++ 11(我使用的是vs2010 sp1)中的C++模板函数参数推导和模板函数重载解析的问题。 我定义了两个模板函数如下:

函数#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 和字符串文字的原因。

关于c++模板函数参数推导和函数解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12258608/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com