Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template with bool parameter

Tags:

I need to implement template with bool parameter. If bool=true, we need to use list container else we need to use vector container.

template <bool isList> 

How can I do it?

like image 412
user3503224 Avatar asked May 17 '14 12:05

user3503224


People also ask

Which is correct example of template parameters?

For example, given a specialization Stack<int>, “int” is a template argument. Instantiation: This is when the compiler generates a regular class, method, or function by substituting each of the template's parameters with a concrete type.

How do you use template arguments in C++?

A template argument for a template template parameter is the name of a class template. When the compiler tries to find a template to match the template template argument, it only considers primary class templates. (A primary template is the template that is being specialized.)

What is a template parameter?

Explanation: A template parameter is a special kind of parameter that can be used to pass a type as argument.

What is a non type template parameter?

A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type. A pointer or reference to a class object.


1 Answers

You have at least three ways to do it.

i. Use std::conditional:

template <bool isList> struct A {     typename std::conditional<isList,                                std::list<int>,                               std::vector<int>>::type container; }; 

ii. Use template specialization for the bool parameter

template <bool isList> struct A;  template<> struct A<true> {     std::list<int> container; };  template<> struct A<false> {     std::vector<int> container; }; 

then

A<true>  a1; // container of a1 is a list A<false> a2; // container of a2 is a vector 

iii. Use template functions

If you need a template function type, then you can do it like below. It returns a container based on the entry parameter.

template <bool isList> auto func() -> typename std::conditional<isList,                                           std::list<int>,                                          std::vector<int>>::type {     typename std::result_of<decltype(func<isList>)&()>::type result;      // ...      return result; }; 

then

auto f1 = func<true>();  // f1 is a list auto f2 = func<false>(); // f2 is a vector 
like image 156
masoud Avatar answered Oct 20 '22 16:10

masoud