c++ - 绑定(bind)到 C++ 模板中非常量引用的常量参数

标签 c++ templates reference constants

考虑这样的事情:

template <typename T>
void f(T& x) 
{
    ....       
}

为什么 const int 绑定(bind)到 f(T&)

在我看来,这有点违反const-correctness。事实上,如果 f() 接受一个 non-const T& 引用,那么很可能 f()修改它的参数(否则,f() 将被定义为 void f(const T&))。

在这样的代码中:

template <typename T>
inline void f(T& x) 
{
    x = 0;
}

int main() 
{
    int n = 2;
    f(n);

    const int cn = 10;
    f(cn);
}

编译器尝试用 T = const int 调用 f(),当然会因为 x = 0; f() 体内的赋值。
这是来自 GCC 的错误消息:

test.cpp: In instantiation of 'void f(T&) [with T = const int]':
test.cpp:13:9:   required from here
test.cpp:4:7: error: assignment of read-only reference 'x'
     x = 0;
       ^

但为什么编译器会尝试将 const 参数与采用-const 参数的函数模板绑定(bind)?

此 C++ 模板规则背后的基本原理是什么?

最佳答案

T 绑定(bind)到 const int

为避免这种情况,您可以使用 SFINAE:

template<typename T>
typename std::enable_if<!std::is_const<T>::value, void>::type
f(T& arg) {}

删除函数:

template <typename T> void f(T& arg) {}
template <typename T> void f(const T&) = delete;

关于c++ - 绑定(bind)到 C++ 模板中非常量引用的常量参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21573541/

相关文章:

c++ - 如何使用此特定容器在 C++ 中创建二维数组

c++ - 如何根据指向的值对双指针数组进行排序?

c++ - 如何处理返回指针的生命周期?

c++ - 在 gdb 调试器中识别符号的源文件名

c++ - 按值发送数组作为参数?

c++ - stringstream 添加一个额外的零

c++ - 为什么虚拟基类必须由最派生的类来构造?

c++ - 模板类和 Friend 模板函数

templates - Play 2.0 模板中 object.member 的模式匹配

c++ - 使用引用修改 const 对象