0

I have browsed similar threads, but none have answered my question. I am looking for a way to ensure correct overload resolution with two competing constructors, where one takes two parameters and the other one is a variadic template constructor. Take this minimal code example:

template<typename Type>
class MyContainer<Type>
{
    public:
        using value_type = Type;
        using size_type = std::size_t;
        using const_reference = const value_type&;

        MyContainer(size_type s = 0)
            : containerSize(s)
        {}

        MyContainer(size_type s, const_reference v)
            : A(s)
        {
            // Assign "s" identical values "v" in the container
        }

        template<typename... Args>
        MyContainer(value_type&& v, Args&&... args)
            :A()
        {
            // Assign each argument as an element of the container
        }

    private:
        size_type containerSize;
}

The problem I am facing is that calling the class constructor without explicitly stating the first parameter's type beforehand, it always calls the variadic template constructor. Here is what happens during code execution:

// This calls the variadic template constructor (how to avoid it?)
MyContainer<int> container(10, 55);

// This calls the variadic template constructor (correct, desired)
MyContainer<int> container(1, 2, 3, 4, 5);

// This calls the "count-copies of value" constructor
MyContainer<int>::size_type containerSize = 10;
MyContainer<int> container(containerSize, 55);

Is there a way to reduce the overhead of declaring containerSize before calling the constructor and making sure it does not invoke the variadic template one?

Mikesz
  • 1
  • 1
    How do you want these two constructors to be distinguished? Anyway, this interface is very non-intuitive. Consider using an explicit [tag](https://stackoverflow.com/questions/20775285/how-to-properly-use-tag-dispatching-to-pick-a-constructor) to differentiate between these two constructors. This will make your code much easier to understand and maintain. – Evg Jun 08 '22 at 08:17
  • please post the real code. The code you did post has numerous errors – 463035818_is_not_an_ai Jun 08 '22 at 08:18
  • The integral constant `10` is considered to have type `int` by the compiler; therefore the conversion to `int&&` is preferred for the first parameter, if you pass `10`. Since the template is very close in signature to the other functions: When exactly do you want it to be called? Only if there are more than 2 parameters or in some other cases as well? – fabian Jun 08 '22 at 08:41
  • This is a minimal example, I thought it should be sufficient for a question. @fabian I would like it to work with any number of parameters. I see there is no workaround the issue, other than what I have shown as possible usage. It's ok, but not as convenient as I would desire. – Mikesz Jun 08 '22 at 08:50

0 Answers0