4

I know questions about the syntax of template default arguments have been asked alot.

Usually, the answer (in sync with my understanding of how it should work) is to use something like that:

template <class T = SomeDefault> class T1 {};

Recently I wanted to check which map implementation Boost uses in its mapped_vector. And found the following snippet:

template<class T, class A>
class mapped_vector:

Apparently, there is no default binding for the argument A, but also apparently, I can instantiate a mapped_vector<int> just fine. Obviosuly a default argument is inferred somehow, but how?

edit: Just to be precise, I am talking about line 279 in this file

4

1 回答 1

7

这里的行(@Xeo 的链接)声明了模板。链接中的行定义了它。注意:如果您决定声明,则不能定义中再次指定默认值。

这有效:(Boost的版本)

template<typename T = int> class A;
template<typename T> class A {};

这不起作用

template<typename T = bool> class A;
template<typename T = int> class A {};

这既不是

template<typename T = int> class A;
template<typename T = int> class A {};

请注意,您必须在其中任何一个中声明它。这有效

template<typename T> class A;
template<typename T = int> class A {};

尽管默认值只能声明一次,但它们不必都在同一部分中声明。这有效,但请不要这样做:

template<class T, class U = bool> class A;
template<class T = int, class U> class A {};

...没有限制,真的。这行得通:(责备 - 或感谢 - @Xeo)

template<class T, class U, class V = double> class A;
template<class T, class U = bool, class V> class A;
template<class T = int, class U, class V> class A {};

当然,您不必包含声明。这有效

template<typename T = int> class A {};
于 2014-06-18T09:21:39.350 回答