pol*_*mma 8 c++ templates reference decltype template-argument-deduction
我已经开始学习C ++,目前我正在尝试使用模板,所以,如果我的措辞不是100%准确的,请多多包涵。
我正在使用以下文献:
第一本书看一下下面的模板函数
template<typename T1, typename T2>
auto max(T1 a, T2 b) -> decltype(b<a?a:b) {
return b < a ? a : b;
}
Run Code Online (Sandbox Code Playgroud)
并指出,这个定义有一个缺点,因为T1或者T2可能是一个参考,因此,返回类型可以是引用类型。
但是,第二本书指出,如果ParamType在我们的情况下T1,T2既不是指针也不是引用(对于我们的情况而言如此),则调用表达式的引用部分将被忽略。
举例说明
template<typename T>
void f(T param);
int x = 27; // as before
const int cx = x; // as before
const int& rx = x; // as before
f(x); // T's and param's types are both int
f(cx); // T's and param's types are again both int
f(rx); // T's and param's types are still both int
Run Code Online (Sandbox Code Playgroud)
现在我想知道,第一个代码片段的返回类型是引用类型,怎么可能呢?
他们都是正确的:
查看cppinsights中生成的代码
template<typename T1, typename T2>
auto max(T1 a, T2 b) -> decltype(b<a?a:b) {
return b < a ? a : b;
}
template<typename T1, typename T2>
auto max2(T1 a, T2 b){
return b < a ? a : b;
}
max(j,i);
max2(j,i);
Run Code Online (Sandbox Code Playgroud)
将“生成”:
template<>
int & max<int, int>(int a, int b)
{
return b < a ? a : b;
}
template<>
int max2<int, int>(int a, int b)
{
return b < a ? a : b;
}
Run Code Online (Sandbox Code Playgroud)
问题出在C ++ 11上(-> decltype(b<a?a:b)如果将其删除)(在C ++ 14及更高版本中),该函数将不再返回引用
static_assert( is_same_v<decltype(i),int> );
static_assert( is_same_v<decltype((i)),int&> );
static_assert( is_same_v<decltype(i+j),int> );
static_assert( is_same_v<decltype(true?i:j),int&> );
Run Code Online (Sandbox Code Playgroud)
参见https://en.cppreference.com/w/cpp/language/operator_other#Conditional_operator
4)如果E2和E3是相同类型和相同值类别的值,则结果具有相同类型和值类别[...]
5)否则,结果为prvalue [...]
在C ++中,这意味着:
static_assert( is_same_v<decltype(true?i:j),int&> ); // E2 and E3 are glvalues
static_assert( is_same_v<decltype(true?i:1),int> ); // Otherwise, the result is a prvalue
Run Code Online (Sandbox Code Playgroud)