【问题标题】:Why is this template expansion legal in C++?为什么这个模板扩展在 C++ 中是合法的?
【发布时间】:2019-03-25 12:12:35
【问题描述】:

考虑以下代码:

template <typename T>
void foo(const T& param) {
    std::cout << __PRETTY_FUNCTION__ << std::endl;
    std::cout << param;
}

int main()
{
    foo<const int&>(5);
    return 0;
}

输出给出:

void foo(const T&) [with T = const int&]                                                                                                                       
5 

这里显然T 被解析为const int&amp;(正如打印输出所说,因为我明确强制这样做)。然而,这似乎产生了一个问题:函数签名采用const T&amp; 类型的参数,在这种情况下它会扩展为const const int&amp; &amp;,这在C++ 中是不合法的语法。

但程序确实运行良好。这里发生了什么?

更新: 我知道T&amp; &amp; 会崩溃为T&amp;。但是,在这种情况下,如果您明确编写它们,双 const 也是不合法的,而且我没有看到模板折叠规则提到这部分。

更新 2: 编译const const int x = 1; 得到error: duplicate ‘const’。 c++ 中不允许使用多个 const (但令人惊讶的是,在 c 中没关系)。

【问题讨论】:

  • T 没有“解决”;你明确地给它参数const int&amp;

标签: c++ templates generics types template-argument-deduction


【解决方案1】:

C++ 类型不是通过文本替换形成的。 const T&amp; 其中Tvoid *void* const &amp;,而不是const void *&amp;

您的代码尝试形成类型“对const T 的左值引用”,其中T 是“对const int 的左值引用”。通过the reference collapsing rules,它将改为形成“对const int 的左值引用”类型。

【讨论】:

  • 值得注意的是,如果您在同一层上确实有多余的 const 会发生什么,例如 const T where typedef const int T
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 2015-11-03
相关资源
最近更新 更多