Adam Varhegyi
Adam Varhegyi

Reputation: 9894

C++ template constructor like these

How could i define a constructor for my class for these constructor calls:

MyClass<std::list<int>, int> myClass1;
 MyClass<std::deque<std::string>, std::string> myClass2;
 MyClass<std::vector<char>, char> myClass3;

I know if it would be:

MyClass<int> myClass1;

I would do like:

template <typename T>
class MyClass{
//...
};

But how could i add entire collections with templates?

Upvotes: 0

Views: 62

Answers (2)

Manu343726
Manu343726

Reputation: 14174

Try with an optional template parameter:

template<typename T , typename VALUE_TYPE = typename T::value_type>
struct SetSecuence
{
  ...
};

However, you could simply store the value type of the containers as a member typedef:

template<typename T>
struct SetSecuence
{
  using value_type = typename T::value_type;
};

This works, as you can see:

using secuence_type_1 = SetSecuence<std::vector<int>>;
using secuence_type_2 = SetSecuence<std::list<bool>>;

secuence_type_1 secuence;
typename secuence_type_1::value_type an_element_of_that_secuence;

Upvotes: 1

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

To get what you asked for, you can simply add another template parameter:

template <typename Cont, typename T>
class SetSequence {
  //...
};

It doesn't matter that it needs to take a container. The container types are just as valid as template arguments as int is.

If the T argument is always going to be the value type of Cont, you can simplify this by having only a single template parameter. Then you can use Cont::value_type to refer to the type of its elements.

Upvotes: 1

Related Questions