總之:因爲使用模板模板參數比使用類型參數更具限制性而沒有提供任何優勢。由於「限制性」我的意思是你可能需要一個更復雜的東西來獲得相同的結果,以「簡單」的類型參數。
爲什麼沒有優勢?
你std::stack
可能已經像這樣的屬性:
template <typename T, typename Container>
struct stack {
Container container;
};
如果更換Container
,通過模板的模板參數,你爲什麼會獲得?
template <typename T, template <typename...> class Container>
struct stack {
Container<T> container;
};
您要爲T
(Container<T>
)實例Container
只有一次,只有,所以模板的模板參數沒有優勢。
爲什麼它更具限制性?
隨着模板的模板參數,你必須傳遞給std::stack
一個模板,露出相同的簽名,例如:
template <typename T, template <typename> class Container>
struct stack;
stack<int, std::vector> // Error: std::vector takes two template arguments
也許你可以使用可變參數模板:
template <typename T, template <typename....> class Container>
struct stack {
Container<T> container;
};
stack<int, std::vector> // Ok, will use std::vector<int, std::allocator<int>>
但什麼如果我不想使用標準std::allocator<int>
?
template <typename T,
template <typename....> class Container = std::vector,
typename Allocator = std::allocator<T>>
struct stack {
Container<T, Allocator> container;
};
stack<int, std::vector, MyAllocator> // Ok...
這變得有點混亂......如果我想使用我自己的容器模板,需要3/4/N參數怎麼辦?
template <typename T,
template <typename... > class Container = std::vector,
typename ...Args>
struct stack {
Container<T, Args...> container;
};
stack<int, MyTemplate, MyParam1, MyParam2> // Ok...
但是,如果我想使用非模板容器?
struct foo { };
struct foo_container{ };
stack<foo, foo_container> // Error!
template <typename... >
using foo_container_template = foo_container;
stack<foo, foo_container_template> // Ok...
與一類參數不存在這樣的問題:
stack<int>
stack<int, std::vector<int, MyAllocator<int>>
stack<int, MyTemplate<int, MyParam1, MyParam2>>
stack<foo, foo_container>
還有其他一些情況下不與模板的模板參數工作,如使用模板接受的混合按特定順序輸入類型和非類型參數,爲此您甚至可以使用可變參數模板創建通用模板模板參數。
@CoryKramer這個問題不是鏈接問題的重複:鏈接的問題詢問我們需要將模板/類型名放在哪裏,而這個問題是關於爲什麼現有類('deque')具有特定的接口,而不是關於句法問題。 – bennofs
默認即使對模板模板參數有效嗎? – anatolyg
@anatolyg是的,他們工作。 –