InsideLoop
InsideLoop

Reputation: 6255

Constructor with template arguments

I have a Dynamic class that can store different types : int, double, std::vector<int>, std::vector<double>, etc. I have about 50 of such types.

I would like my Dynamic type to have a constructor where we give two informations:

I am looking forward to something such as

const Dynamic x<std::vector<double>>{10};

to construct in place a Dynamic object that has a std::vector<double> of length 10.

PS: I am allowed to use C++11 and I am not allowed to use RTTI

Upvotes: 0

Views: 642

Answers (2)

Mark B
Mark B

Reputation: 96233

As long as you don't mind putting the type info next to Dynamic rather than the variable name you can do this with variadic args:

#include <iostream>
#include <vector>

template <typename T>
class Dynamic
{
public:
    template <typename... Args>
    Dynamic(Args... args) : data_(args...)
    {
    }

    T data_;
};

int main()
{
    const Dynamic<std::vector<double>> x{10};

    std::cout << x.data_.size() << std::endl;
}

Upvotes: 0

Fran&#231;ois Andrieux
Fran&#231;ois Andrieux

Reputation: 29013

Constructor template arguments must be deduced. They cannot be provided explicitly. You can get around this by providing a type tag which encodes the wanted template argument and passing it as an additional constructor argument. For example :

#include <utility>  // For std::forward

struct foo
{
    // Helper tag type
    template<class T>
    struct type_tag {};

    // The template argument T is deduced from type_tag<T>
    template<class T, class ... Args>
    foo(type_tag<T>, Args&&... p_args)
    {
        T value{ std::forward<Args>(p_args)... };
    }
};

int main()
{
    // Provide a type tag so the template argument can be deduced
    foo bar{ foo::type_tag<int>{}, 5 };
}

Upvotes: 4

Related Questions