Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Template parameter

Is it possible to have optional template parameter in C++ , for example

template < class T, class U, class V>
class Test {
};

Here I want user to use this class either with V or without V

Is following possible

Test<int,int,int> WithAllParameter
Test<int,int> WithOneMissing

If Yes how to do this.

like image 903
Avinash Avatar asked Oct 16 '11 20:10

Avinash


People also ask

What can be a template parameter?

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.)

Why do we use :: template template parameter?

8. Why we use :: template-template parameter? Explanation: It is used to adapt a policy into binary ones.

What is a template parameter?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

What is non-type template parameters?

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.


2 Answers

You can have default template arguments, which are sufficient for your purposes:

template<class T, class U = T, class V = U>
class Test
{ };

Now the following work:

Test<int> a;           // Test<int, int, int>
Test<double, float> b; // Test<double, float, float>
like image 97
ildjarn Avatar answered Oct 05 '22 05:10

ildjarn


Sure, you can have default template parameters:

template <typename T, typename U, typename V = U>

template <typename T, typename U = int, typename V = std::vector<U> >

The standard library does this all the time -- most containers take two to five parameters! For example, unordered_map is actually:

template<
    class Key,                        // needed, key type
    class T,                          // needed, mapped type
    class Hash = std::hash<Key>,      // hash functor, defaults to std::hash<Key>
    class KeyEqual = std::equal_to<Key>, // comparator, defaults to Key::operator==()
    class Allocator = std::allocator<std::pair<const Key, T>> // allocator, defaults to std::allocator
> class unordered_map;

Typicall you just use it as std::unordered_map<std::string, double> without giving it any further thought.

like image 24
Kerrek SB Avatar answered Oct 05 '22 05:10

Kerrek SB