显式传递模板参数时,函数模板参数会丢失常量吗?

Veg*_*eta 4 c++ template-argument-deduction

template <typename T>
void test(const T& x) {}

int a {};
int& ref = a;
const int& c_ref = a;

test(c_ref)  // T = int, x = const int&
test<int&>(ref); // T = int& , x = int&
Run Code Online (Sandbox Code Playgroud)

为什么函数模板参数 x 失去了const限定符?

lub*_*bgr 8

在显式(非推导)实例化中

test<int&>(ref);
Run Code Online (Sandbox Code Playgroud)

这是你得到的(理论)签名

void test<int&>(const (int&)& x)
Run Code Online (Sandbox Code Playgroud)

这表明const-qualification 适用于整体(int&),而不仅仅是int. const适用于剩下的东西,如果什么都没有,它适用于正确的东西: int&,但作为一个整体 - 在那里,它适用于&,再次因为const适用于它左边的东西。但是没有const引用(它们根本不能改变,即它们不能重新绑定),const被删除,并且引用折叠规则将两者&合二为一。