gpt4 book ai didi

c++ - 为什么 T& 类型的模板函数参数可以绑定(bind)到 const 左值而不是右值?

转载 作者:可可西里 更新时间:2023-11-01 18:29:05 26 4
gpt4 key购买 nike

考虑:

template <typename T> void f(T&);

const int b = 2;
f(b); // ok
f(2); // error, can not bind rvalue to lvalue reference

为什么是f(const int)允许?逻辑似乎表明,如果程序员没有明确定义模板参数为 const T& ,他/她想修改绑定(bind)变量。

所以在这种情况下,问题是,为什么模板实例化在没有明确要求的情况下让自己可以自由地使用 consts 进行实例化?

即使有允许模板实例化用 const 实例化的理由,那么为什么在那种情况下会禁止绑定(bind)到右值?您可以将右值绑定(bind)到 const 左值引用。在这种情况下,模板将被实例化为 f<const int> , 和 f(2)将被允许​​。

我想知道这些决定背后的原因,而不是对标准的引用。

最佳答案

Why is f(const int) allowed?

您可以替换模板 T通过 const int改造 T&进入const int&

Even if there was a rationale for allowing template instantiation to instantiate with consts, then why, in that case, would be binding to rvalues forbidden?

没有T (在 T& 中)(完全)匹配 int&&扣除。

f<const int>(42)是允许的,但不会发生扣除。

I want to know the reasoning behind these decisions, not references to the standard.

那么为什么允许在模板中替换 cv?
我会说它使泛型编程更容易。
否则,您必须为 const 的每个组合提供重载。 , volatile .

这里如果要限制T到非const ,您可以使用具有以下特征的 SFINAE:

template <typename T> std::enable_if_t<!std::is_const<T>::value> f(T&);

关于c++ - 为什么 T& 类型的模板函数参数可以绑定(bind)到 const 左值而不是右值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47273746/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com