2011-10-16 33 views
26

Czy to możliwe, aby mieć opcjonalny parametr szablonu w C++, na przykładOpcjonalny parametr szablonu

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

Tutaj chcę użytkownika, aby użyć tej klasy albo z V lub bez V

obserwuje możliwe

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

Jeśli tak, jak to zrobić.

Odpowiedz

24

Można mieć domyślny argumenty szablonów, które są wystarczające do swoich celów:

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

teraz następujące prace:

Test<int> a;   // Test<int, int, int> 
Test<double, float> b; // Test<double, float, float> 
27

Oczywiście, można mieć domyślne parametry szablonu:

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

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

Standardowa biblioteka robi to cały czas - większość pojemników trwać od dwóch do pięciu parametrów! Na przykład, unordered_map jest rzeczywiście:

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 po prostu użyć go jako std::unordered_map<std::string, double> nie dając mu żadnych dalszych myśli.

Powiązane problemy