Avoiding implicit conversion in constructor. The 'explicit' keyword doesn't help here

前端 未结 7 1990
闹比i
闹比i 2020-12-29 18:07

I am able to avoid the implicit conversion of a constructor using the explicit keyword. So now, conversions like A a1 = 10; can be avoided.

7条回答
  •  生来不讨喜
    2020-12-29 18:24

    You can delete A::A();:

    struct A
    {
        explicit A(int a)
        : num(a)
        {}
    
        template
        A(T) = delete;
    
        int num;
    };
    
    int main()
    {
        //A a1=A(10.0); // error: use of deleted function 'A::A(T) [with T = double]'
        A a2 = A(10); // OK
        (void) a2;
    }
    

    Demo: https://coliru.stacked-crooked.com/a/425afc19003697c9

提交回复
热议问题