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?
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.
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.)
Explanation: A template parameter is a special kind of parameter that can be used to pass a type as argument.
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.
You have at least three ways to do it.
template <bool isList> struct A {     typename std::conditional<isList,                                std::list<int>,                               std::vector<int>>::type container; }; bool parametertemplate <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 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 If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With