Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anyway to disambiguate constructor selection?

Tags:

c++

I have a small code like this:

class A {
public:
    A() {
        std::cout << "ctor\n";
    }

    A(int i = 5) {
        std::cout << "ctor -> v\n";
    }

    virtual ~A() {
        std::cout << "dtor\n";
    }
};

int main() {
    A a;
}

It is is obvious that this code won't compile because A's constructor is ambiguous. I wonder if there is anyway to disambiguate this code by manually selecting which constructor to call. I don't want to pass default value in order to disambiguate function call (which is a obvious approach). I just want to know if there is any other way or not.

like image 420
Afshin Avatar asked Nov 07 '25 03:11

Afshin


1 Answers

Without changing the constructor definitions there is no way in standard C++ to disambiguate the call.

Your options for clearing the ambiguity are to either remove the default argument, or to add a "dummy" tag argument to the first constructor.

constexpr struct default_tag_t{} default_tag{};
///
A(default_tag_t) {
    std::cout << "ctor\n";
}

Which makes the first constructor uniquely callable with

A a(default_tag);
like image 51
StoryTeller - Unslander Monica Avatar answered Nov 08 '25 18:11

StoryTeller - Unslander Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!