我有一个模板,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>
将少一个参数,并且不会有额外的数据成员。
这可能吗?我可以在不更改 、 和 的定义的情况下编译以下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;
}