绑定到C ++模板中非常量引用的常量参数 [英] Const arguments binding to non-const references in C++ templates

查看:69
本文介绍了绑定到C ++模板中非常量引用的常量参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

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

为什么像 const int 这样的东西绑定到 f(T&)

Why does something like const int binds to f(T&)?

在我看来,这违反了 const-correctness em>。实际上,如果 f()采用 non -const T& 引用,则 f()很可能会修改其参数(否则, f()会被定义为 void f(const T&))。

This seems to me kind of a violation of const-correctness. In fact, if f() takes a non-const T& reference, then it's very likely that f() will modify its argument (else, f() would have been defined as 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);
}

编译器尝试调用 f() T = const int ,那么由于 x = 0; f()体内的赋值。

这是来自GCC的错误消息:

the compiler tries to call f() with T = const int, then of course there is an error message because of the x = 0; assignment inside f()'s body.
This is the error message from 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 参数与带有 non -const参数的函数模板的函数?

But why does the compiler try to bind a const argument with a function template which takes a non-const parameter?

合理价格是多少放在此C ++模板规则后面?

What's the rationale behind this C++ template rule?

推荐答案

您可以使用 std :: enable_if 加上例如 std :: is_const 可以避免 T 绑定到 const

You can use std::enable_if plus e.g. std::is_const to avoid that T binds to a const type.

Re…

Re …


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

“What's the rationale behind this C++ template rule?”

它可能在Bjarne的设计中可以找到- -进化书,但最常见的理由是选择规则是为了简单和统一,因此似乎也出现在这里:以特殊方式处理某些类型会引入不必要的复杂性。

it can possibly be found in Bjarne's design-and-evolution book, but about the most common rationale is that the rules have been chosen for simplicity and uniformity, and so it appears to be also here: treating some types in special ways would introduce needless complexity.

这篇关于绑定到C ++模板中非常量引用的常量参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆