可选的Template参数

时间:2011-10-16 20:47:29

标签: c++ templates optional-parameters

是否可以在C ++中使用可选的模板参数,例如

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

我希望用户在VV

的情况下使用此课程

是否可能

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

如果是,如何做到这一点。

2 个答案:

答案 0 :(得分:28)

当然,您可以使用默认模板参数:

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

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

标准库一直这样做 - 大多数容器需要两到五个参数!例如,unordered_map实际上是:

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;

您只需将其用作std::unordered_map<std::string, double>而不再进一步考虑。

答案 1 :(得分:26)

您可以拥有默认模板参数,这些参数足以满足您的目的:

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

现在进行以下工作:

Test<int> a;           // Test<int, int, int>
Test<double, float> b; // Test<double, float, float>
相关问题