Implicit constructor argument conversion in C++11

前端 未结 3 417
礼貌的吻别
礼貌的吻别 2021-01-21 07:57

Lets concider following code:

class A{
public:
  A(int x){}
};

class B{
public:
  B(A a){};
};


int main() {
  B b = 5;
  return 0;
}

And whi

3条回答
  •  死守一世寂寞
    2021-01-21 08:11

    You can use a converting constructor that is constrained on conversions to A.

    class B {
    public:
        // It doesn't hurt to keep that one
        B(A a){};
    
        template<
            typename T
            , EnableIf>...
        >
        B(T&& value)
        {
            // How to use the value
            A a = std::forward(value);
        }
    };
    
    // Now B b = foo; is valid iff A a = foo; is, except for a few exceptions
    

    Make sure you understand the purpose of the EnableIf constraint. If you do not use it, you will face gnarly compilation errors, or worse: no errors at all. You should also carefully consider if making B convertible from potentially lots of types is at all worth it. Implicit conversions tend to make a program harder to understand, and that can quickly outweigh the apparent benefits they give.

提交回复
热议问题