Why can I prevent implicit conversions for primitives but not user-defined types?

前端 未结 3 1656
轮回少年
轮回少年 2021-01-25 18:16

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

相关标签:
3条回答
  • 2021-01-25 18:32

    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);
    

    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.

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

    0 讨论(0)
  • 2021-01-25 18:46

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

    No, only a forwarding reference overload disables ICS (Implicit Conversion Sequence) for all other overloads in the overload set. Make it a forwarding reference, and see ICS disabled (Coliru Link)

    template <class T>
    void foo(const T&&) = delete;  // introduces a qualification match
    

    The above code adds a qualification match to the overload. Thus, ICS is still in play.

    Why foo(3.3) failed is because 3.3 is an prvalue of type double which will match better with the rvalue overload than converting to int. Because qualification match is ranked better than a conversion match

    0 讨论(0)
  • 2021-01-25 18:54

    There are 3 possible overloads

    • 1 is viable.
    • 2 is viable
    • 3 isn't

    2 is better match (template (non exact match) vs regular method (with one user define conversion)).

    You may look at http://en.cppreference.com/w/cpp/language/overload_resolution to see a complete set of rules needed

    0 讨论(0)
提交回复
热议问题