为什么我可以防止对基元的隐式转换,而不是用户定义类型的隐式转换? [英] Why can I prevent implicit conversions for primitives but not user-defined types?

查看:45
本文介绍了为什么我可以防止对基元的隐式转换,而不是用户定义类型的隐式转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

High Integrity C ++标准建议可以删除函数的右值参数,从而防止隐式转换.

The High Integrity C++ Standards suggest that rvalue arguments to functions can be deleted thus preventing implicit conversions.

http://www.codingstandard.com/rule/8-3-4-define-delete-functions-with-parameters-of-type-rvalue-reference-to-const/

我发现原语和用户定义类型的行为非常不同.

I've found that the behaviour for primitives and user-defined types is very different.

struct A { };

struct B { B(const A& ) {} };

template <class T>
void foo(const T&&) = delete;  // 1 - deleted rvalue overload. const intentional.

void foo(B) {}                 // 2

void foo(int) {}               // 3

int main(int argc, char* argv[])
{
  A a;
  foo(a);   // This resolves to 2
  foo(3.3); // This resolves to 1
  foo(2);   // This resolves to 3 (as expected).
}       

为什么删除的右值重载会阻止隐式转换为int而不是从一种用户定义类型转换为另一种类型?

Why does a deleted rvalue overload prevent an implicit conversion to int but not from one user-defined type to another?

推荐答案

在您的代码中,用户定义类型和原始类型之间的处理没有区别.这两行的行为之间的区别:

In your code, there is no difference in treatment between user-defined types and primitive types. The difference between the behaviour of these two lines:

foo(a);
foo(3.3);

a 是一个左值,而 3.3 是一个右值.rvalue参数与您的重载 1 (仅接受rvalues)匹配,而lvalue参数不匹配.

is that a is an lvalue, and 3.3 is an rvalue. The rvalue argument matches your overload 1 (which only accepts rvalues), the lvalue argument does not.

如果您尝试使用右值参数调用 foo< A> ,它也会匹配 1 并失败,例如 foo(A {}); .

If you try to invoke foo<A> with an rvalue argument it will also match 1 and fail, e.g. foo(A{});.

这篇关于为什么我可以防止对基元的隐式转换,而不是用户定义类型的隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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