Afshin
Afshin

Reputation: 9173

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

Upvotes: 2

Views: 87

Answers (2)

phuclv
phuclv

Reputation: 41814

Why don't just cast to the correct type? 1 is an int literal so it makes some "confusion" when passing to unsigned parameters

int main() {
    S s;
    s.f(1, (uint8_t)1);
    s.f(1, (uint32_t)1);
    s.f(1, 1U);
}

Demo on Godlbolt

Upvotes: 2

Jeremy Friesner
Jeremy Friesner

Reputation: 73091

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.

Upvotes: 4

Related Questions