我有一个模板,template <typename T> class wrapper
,我想专门基于typename T::context_type
的存在。如果声明了typename T::context_type
,那么wrapper<T>
实例化的构造函数和赋值运算符重载应接受强制参数typename T::context_type
。此外,wrapper<T>
对象会将“上下文”存储在成员数据中。如果typename T::context_type
不存在,那么wrapper<T>
的构造函数和赋值运算符重载只需要少一个参数,并且不会有其他数据成员。是否有可能基于模板类型参数的嵌套typedef的存在来专门化模板定义?
这可能吗?我可以在不更改config1
,config2
和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;
}
你需要做的像'类型名称void_ :: type'来确保专业化是有效的*和*第二个参数匹配默认参数'void'。 –
@Luc Danton:我后面的实际想法是,由于SFINAE的缘故,没有内部'context_type'的类型'T'不会选择专业化。 –
对于那些没有嵌套类型的类型来说,特化将是无效的,但是如果'T :: context_type'是'int',那么特化是'wrappper'并且不匹配主模板'包装',这就是为什么我的意思是“它不匹配”。 –