BlueSun
BlueSun

Reputation: 3570

Creating a constructor for a template class which calls the template initialization within a vector

If I want to create a template class that is able to call the constructor of the template (within the class constructor), is this the way to do it? Or is there a better solution?

template<typename T>
class A{
public:
    A(int n): mVector(n) {}                //normal constructor
    A(int n, auto a): mVector(n, T(a)) {}  //constructor with template initialization
private:
    std::vector<T> mVector;
};

Also is there a way to extend this for arbitrary amount of Parameters T(a,b,c,...) without having a constructor for every case?

Upvotes: 1

Views: 89

Answers (1)

Columbo
Columbo

Reputation: 60979

Perhaps you're searching for this:

template <typename... Args>
A(int n, Args&&... args) : // First argument should probably be std::size_t
    mVector(n, T(std::forward<Args>(args)...)) {}

However, you could just take a const T& and expect the caller to give you one.

Upvotes: 6

Related Questions