为模板参数使用 typedefed 默认类型 [英] Using a typedefed default type for template parameter
问题描述
我有一个类,我希望模板参数 B 具有默认类型.问题是默认类型是一个复杂的表达式,也取决于 A 的类型.
I have a class where I want the template parameter B to have a default type. The problem is that the default type is a complicated expression depending also on the type of A.
下面的代码说明了这种情况,但显然不能编译,因为模板表达式中不知道defaultB类型.
The following code illustrates the situation but does obviously not compile, because defaultB type is not know inside the template expression.
template<class A, class B = defaultB>
class Foo{
typedef A::Bar Bar;
typedef Bar::Ex defaultB;
};
有人知道如何正确解决这个问题吗?
Does anybody have an idea how to solve this problem properly?
推荐答案
你可以像这样维护一个默认的命名空间:
You could maintain a namespace of defaults like this:
namespace detail {
template <typename A>
using defaultB = typename A::Bar::Ex;
}
template<class A, class B = typename detail::defaultB<A>>
class Foo{
};
这使您可以在 detail
命名空间中拥有任意复杂的表达式,而不会使 Foo
声明变得丑陋.
This lets you have as complex expressions as you like in your detail
namespace without making the Foo
declaration ugly.
这篇关于为模板参数使用 typedefed 默认类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!