我有一个 T& ,它有一个函数的常量和非常量版本。我想调用该函数的 const 版本。我尝试使用 std::add_const 将 T& 转换为 const T& 但它不起作用。我做错了什么以及如何解决它?
这是一个简单的例子。
void f(int&)
{
std::cout << "int&" << std::endl;
}
void f(const int&)
{
std::cout << "const int&" << std::endl;
}
int main()
{
int a = 0;
int& r = a;
f(static_cast<std::add_const<decltype (r)>::type>(r));
}
Output: int&
类型特征是解决这个问题的一种非常费力的方法。简单的使用模板类型推导:
void f(int&)
{
std::cout << "int&" << std::endl;
}
void f(const int&)
{
std::cout << "const int&" << std::endl;
}
template<typename T>
const T& make_const(T& t) { return t; }
int main()
{
int a = 0;
int& r = a;
f(make_const(r));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)