可选的Template参数

Avi*_*ash 28 c++ templates optional-parameters

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

template < class T, class U, class V>
class Test {
};
Run Code Online (Sandbox Code Playgroud)

在这里,我希望用户使用V或不使用此类V

是否可能

Test<int,int,int> WithAllParameter
Test<int,int> WithOneMissing
Run Code Online (Sandbox Code Playgroud)

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

Ker*_* SB 28

当然,您可以拥有默认模板参数:

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

template <typename T, typename U = int, typename V = std::vector<U> >
Run Code Online (Sandbox Code Playgroud)

标准库一直这样做 - 大多数容器需要两到五个参数!例如,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;
Run Code Online (Sandbox Code Playgroud)

您只需使用它,std::unordered_map<std::string, double>而无需进一步考虑.


ild*_*arn 27

您可以使用默认模板参数,这些参数足以满足您的需要:

template<class T, class U = T, class V = U>
class Test
{ };
Run Code Online (Sandbox Code Playgroud)

现在做以下工作:

Test<int> a;           // Test<int, int, int>
Test<double, float> b; // Test<double, float, float>
Run Code Online (Sandbox Code Playgroud)