Optional Template parameter

时间秒杀一切 提交于 2019-12-29 04:29:06

问题


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.


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/7787208/optional-template-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!