【发布时间】: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&(正如打印输出所说,因为我明确强制这样做)。然而,这似乎产生了一个问题:函数签名采用const T& 类型的参数,在这种情况下它会扩展为const const int& &,这在C++ 中是不合法的语法。
但程序确实运行良好。这里发生了什么?
更新:
我知道T& & 会崩溃为T&。但是,在这种情况下,如果您明确编写它们,双 const 也是不合法的,而且我没有看到模板折叠规则提到这部分。
更新 2:
编译const const int x = 1; 得到error: duplicate ‘const’。 c++ 中不允许使用多个 const (但令人惊讶的是,在 c 中没关系)。
【问题讨论】:
-
T没有“解决”;你明确地给它参数const int&
标签: c++ templates generics types template-argument-deduction