Home > database >  C template constructor ambiguity used when it shouldn't
C template constructor ambiguity used when it shouldn't

Time:12-22

I have got an issue because when instantiating a class object, the implementation is using the wrong constructor obtained through a template rather than the suitable one.

Here is a simplified version of the code:

dummy.h

#ifndef GUARD_dummy
#define GUARD_dummy

#include <vector>

class Dummy {

    public:
        Dummy() {}
        explicit Dummy(std::vector<int>::size_type n, const int& val = 0): data(n, val) {}
        template <class In>
            Dummy(In b, In e) { create(b, e); }
    private:
        std::vector<int> data;

        template <class In>
            void create(In, In);
};

template <class In>
    void Dummy::create(In b, In e) {
        std::copy(b, e, std::back_inserter(data));
    }

#endif

test.cpp

#include "dummy.h"

int main() {
    Dummy v(3, 4);
    return 0;
}

I expect the constructor Dummy(size_type, const int&) to be used. Why is it not happening? In which ways can I overcome this issue?

Thank you!

SOLUTION

#include "dummy.h"

int main() {
    const size_t dim = 3;
    Dummy v(dim, 4);
    return 0;
}

New question

If let's say I had defined the constructor as Dummy(int, const int&). In that case, would the code be wrong? Should I delete one of the constructors to solve ambiguity?

Thanks again!

CodePudding user response:

The constant 3 will naturally evaluate as int. It needs to be converted to size_type to use the first constructor. For any overloaded function, including constructors, the one requiring the fewest conversions will be preferred.

CodePudding user response:

#include "dummy.h"

int main() {
    int four = 4;
    Dummy v( static_cast<size_t>(3), four);
    return 0;
}

The C automatic type conversions were not finding your template specialization from the types you provided in the ctor where were signed int types by default.

  • Related