我有一个模板,template <typename T> class wrapper
,我想根据存在的情况进行专门研究typename T::context_type
. If typename T::context_type
声明后,则构造函数和赋值运算符重载wrapper<T>
实例化应该接受强制typename T::context_type
范围。此外,wrapper<T>
对象将在成员数据中存储“上下文”。如果typename T::context_type
不存在,则构造函数和赋值运算符重载wrapper<T>
将少一个参数并且不会有额外的数据成员。
这可能吗?我可以在不更改定义的情况下编译以下代码吗config1
, config2
, and main()
?
#include <iostream>
template <typename T, bool context_type_defined = true>
class wrapper
{
public:
typedef typename T::context_type context_type;
private:
context_type ctx;
public:
wrapper(context_type ctx_)
: ctx(ctx_)
{
std::cout << "T::context_type exists." << std::endl;
}
};
template <typename T>
class wrapper<T, false>
{
public:
wrapper() {
std::cout << "T::context_type does not exist." << std::endl;
}
};
class config1 {
public:
typedef int context_type;
};
class config2 {
public:
};
int main()
{
wrapper<config1> w1(0);
wrapper<config2> w2;
}
对的,这是可能的。我过去曾通过使用一些元编程技巧来实现这种行为。基本构建块是:
BOOST_MPL_HAS_XXX_TRAIT_DEF
,定义一个元函数谓词,如果参数是类类型并且具有给定名称的嵌套类型(在您的情况下为 context_type ),则该谓词将计算为真实类型。
http://www.boost.org/doc/libs/1_47_0/libs/mpl/doc/refmanual/has-xxx-trait-def.html http://www.boost.org/doc/libs/1_47_0/libs/mpl/doc/refmanual/has-xxx-trait-def.html
Boost.EnableIf
,根据先前定义的特征来定义专业化。
http://www.boost.org/libs/utility/enable_if.html http://www.boost.org/libs/utility/enable_if.html# 请参阅 3.1 启用模板类特化
请注意,您也许可以直接与 SFINAE 一起使用该行为,类似这样的操作可能会起作用:
template< typename T, typename Context = void >
class wrapper { ... }; // Base definition
template< typename T >
class wrapper< T, typename voif_mfn< typename T::context_type >::type > { ... }; // Specialization
但是,我喜欢基于特征和启用 if 的解决方案的表现力。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)