gpt4 book ai didi

c++ - 模板参数是否可以是引用类型?

转载 作者:可可西里 更新时间:2023-11-01 17:53:06 30 4
gpt4 key购买 nike

我已经开始学习 C++,目前我正在尝试开始使用模板,所以如果我的措辞不是 100% 准确,请多多包涵。

我正在使用以下文献:

  • C++ 模板:完整指南(第 2 版)
  • 有效的现代 C++:改进 C++11 和 C++14 使用的 42 种具体方法

第一本书看看下面的模板函数

template<typename T1, typename T2>
auto max(T1 a, T2 b) -> decltype(b<a?a:b) {
return b < a ? a : b;
}

并声明此定义有一个缺点,因为 T1T2 可能是引用,因此返回类型可能是引用类型。

然而,第二本书指出,如果 ParamType,在我们的例子中 T1T2 既不是指针也不是引用,这对于我们的情况是正确的,调用表达式的引用部分将被忽略。

举例说明

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

现在我想知道,第一个代码片段的返回类型怎么可能是引用类型?

最佳答案

他们都是对的:

查看 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);

将“生成”:

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;
}

麻烦是关于 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&> );

参见 https://en.cppreference.com/w/cpp/language/operator_other#Conditional_operator

4) If E2 and E3 are glvalues of the same type and the same value category, then the result has the same type and value category [...]

5) Otherwise, the result is a 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

关于c++ - 模板参数是否可以是引用类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55746202/

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