Search code examples
c++overload-resolution

Selecting ambiguous constructor manually


When a call to a function (member class function or free function) is ambiguous, we can select it easily using static_cast<> to the function type we calling:

struct S {
    void f(uint32_t, uint8_t) {
        std::cout << "1\n";
    }

    void f(uint32_t, uint32_t) {
        std::cout << "2\n";
    }
};

int main() {
    S s;
    auto f1 = static_cast<void(S::*)(uint32_t, uint8_t)>(&S::f);
    (s.*f1)(1,1);
    auto f2 = static_cast<void(S::*)(uint32_t, uint32_t)>(&S::f);
    (s.*f2)(1,1);
}

But I wonder if it is possible to do something similar for constructors. For example, in the following structure:

struct S {
    S(uint32_t, uint8_t) {
        std::cout << "1\n";
    }

    S(uint32_t, uint32_t) {
        std::cout << "2\n";
    }
};

Is it possible to manually solve ambiguous constructor call for creating S s(1,1);?


Solution

  • Is this what you had in mind?

    S s1(static_cast<uint32_t>(1), static_cast<uint32_t>(2));
    S s2(static_cast<uint32_t>(1), static_cast<uint8_t>(2));
    

    This disambiguates the constructor-calls by specifying the types explicitly in the arguments.