我有以下情况,我想实例化模板类型的对象。我希望模板类型对象的实例化取决于“实例化器”类。
template <class T>
class Base
{
public:
Base(){}
void do_something()
{
T obj = this->Test();
// do something with object
}
virtual T Test()
{
return T(5);
}
};
template <class T>
class Derived : public Base<T>
{
public:
Derived() : Base<T>() {}
virtual T Test()
{
return T(5, 6);
}
};
class Test1
{
public:
Test1(int x){}
};
class Test2 : public Test1
{
public:
Test2(int x, int y) : Test1(x) {}
};
稍后在我的代码中,我想使用基础或派生对象。它们对功能obj
中的模板类型对象(do_something()
)执行操作。我想让obj
的实例化取决于实现Test()
功能的功能。Base
仅应与具有相同构造函数的Test1
类型的对象或Test1
的派生类一起使用。Derived
应该只对与Test2
具有相同构造函数的对象起作用。
Base<Test1>(); // works
Base<Test2>(); // doesn't work, but should not work by my design and throw a compile error
Derived<Test1>(); // same
Derived<Test2>(); // should work, but doesn't,
// since Base::Test() still exists, but cannot be compiled due to wrong constructor of T
是否有实现上述行为的方法?还是我可以进行设计更改?
您可能将Base更改为对于任何T
都是正确的:
template <class T>
class Base
{
public:
Base(){}
void do_something()
{
T obj = this->Test();
// do something with object
}
virtual T Test()
{
if constexpr (std::is_constructible_v<T, int>) {
return T(5);
}
throw std::runtime_error("should not be called");
}
};