问题描述
所以我试图了解Boost的ptree
实现的情况.
So I'm trying to understand what's happening with Boost's ptree
implementation.
在ptree.hpp中实际上定义了basic_ptree
:
In ptree.hpp basic_ptree
is actually defined:
template<class Key, class Data, class KeyCompare>
class basic_ptree
在ptree_fwd.hpp中,看起来像basic_ptree
的前向声明,但是具有新的模板参数默认值:
In ptree_fwd.hpp there is what looks like a forward declaration of basic_ptree
but with a new template argument default:
template < class Key, class Data, class KeyCompare = std::less<Key> >
class basic_ptree;
最后在ptree_fwd.hpp中,ptree
是typedef
d:
And finally in ptree_fwd.hpp ptree
is typedef
'd:
typedef basic_ptree<std::string, std::string> ptree;
然后是ptree_fwd.hpp中的前向声明,对不对?因此,允许我在前向声明中默认使用模板参数吗?
This is a forward declaration then in ptree_fwd.hpp, right? So I am allowed to default a template argument in a forward declaration?
推荐答案
是的,可以.但是,每个默认模板参数只能指定一次.
Yes, you can. But you can specify each default template argument only once.
[示例:
template<class T1, class T2 = int> class A;
template<class T1 = int, class T2> class A;
等同于
template<class T1 = int, class T2 = int> class A;
-示例]
和 17.1/16
template<class T = int> class X;
template<class T = int> class X { /* ... */ }; // error
-示例]
(请注意,这些取自最新草案,但据我所知,近年来这些规则并没有改变.)
( Note, these are taken from the latest draft, but these rules haven't changed in recent years to my knowledge )
如果只希望知道声明就可以使用默认参数,则必须在声明中定义它们.上面还回答了您在评论中提出的问题:
If you want to be able to make use of the default arguments when only the declaration is know, you'd have to define them in the declaration. Above also answers the question that you asked in the comments:
如果这样做,您的程序将格式错误,因为只允许一次指定每个默认参数.拥有两个声明(其中一个定义默认参数,另一个没有定义)并不会真正引起任何问题,因为它们彼此之间没有分歧.这仅意味着,如果仅知道没有默认版本的版本,则在实例化模板时必须指定 all 参数.
If you did that your program would be ill-formed, as you are allowed to specify each default argument only once. Having two declarations, where one defines the default arguments and the other doesn't, does not really cause any problems because they are not in disagreement of eachother. It only means that if only the version without defaults is known, you'd have to specify all arguments when instantiating your template.
我个人的观点是,在标头中只包含一个声明,用于指定默认的模板参数,然后在需要该声明的位置(以及定义)包括该标头.
My personal opinion would be to have only one declaration in a header that specifies the default template arguments, and then include that header wherever you need the declaration (and for the definition as well).
这篇关于我是否可以默认转发声明中的模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!