【发布时间】:2022-06-15 21:22:34
【问题描述】:
我想设计一个带有两个参数的模板类,这些参数在编译时基于两个互斥基类之一的模板参数继承。
我想对我来说保持简单,所以想出了这个工作示例。我基于模板参数使用std::conditional 获得的继承条件。我使用std::enable_if 设置的条件继承的专用方法。
class Empty {};
template<typename T>
class NonEmpty { protected: std::vector<T> mObjects; };
template< typename A, typename B = A>
class Storage : public std::conditional<std::is_same<A, B>::value, Empty, NonEmpty<B>>::type
{
public:
template<typename C = B, typename std::enable_if<std::is_same<C, A>::value>::type* = nullptr>
void doStuff()
{
// one argument or two arguments with same type
// do stuff ...
};
template<typename C = B, typename std::enable_if<std::is_same<C, A>::value>::type* = nullptr>
void doSomthingElse()
{
// one argument or two arguments with same type
// do something exclusively just for this argument constellation ...
};
template<typename C = B, typename std::enable_if<!std::is_same<C, A>::value>::type* = nullptr>
void doStuff()
{
// two arguments with different types
// do stuff with inherited variables of NonEmpty-Class ...
};
};
int main()
{
EmptyClass<int> emp;
NonEmptyClass<int, float> nonemp;
emp.doStuff();
emp.doSomethingElse();
nonemp.doStuff();
}
有没有更好的方法来解决这个问题,或者我现有的解决方案有什么改进? (我在 C++ 14 中使用 GCC 8.1.0)
【问题讨论】:
-
部分专业化是一回事。
标签: c++ templates inheritance conditional-statements enable-if