这种编译时确定继承的模式有名字吗

Does this pattern of compile time determination of inheritance have a name?

本文关键字:模式 继承 编译      更新时间:2023-10-16

最近,我一直在开发一个C++11库,我已经使用过几次这种模式,其中实际要向用户公开的类根据包含的类型确定其继承的类。我在这里复制了我用来实现这一点的va_if变元函数,但这也可以用boost::mpl::if_cstd::conditional来实现。

template<typename bool_type, typename result_type, typename... Ts>
struct va_if;
template<typename result_type, typename... Ts>
struct va_if<std::true_type, result_type, Ts...>
{
  typedef result_type type;
};
template<typename result_type, typename... Ts>
struct va_if<std::false_type, result_type, Ts...>
{
  typedef typename va_if<Ts...>::type type;
};
template<typename T>
class container_base { /* Generic container functions */ };
template<typename T>
class container_integral_base
  : public container_base<T>
{ /* Code tailored to integral types */ };
template<typename T>
class container_floating_point_base
  : public container_base<T>
{ /* Code tailored to floating point types */ };
// This class chooses the class it should inherit from at compile time...    
template<typename T>
class Container
  : public va_if<std::is_integral<T>::type, container_integral_base<T>,
                 std::is_floating_point<T>::type, container_floating_point_base<T>>::type
{ /* public interface code */ };

我想知道的是,这种编译时确定继承的模式有名字吗?

我想我以前没有见过这种模式与可变模板一起使用,尽管在多个库中可以看到与专业化类似的方法:

enum container_type { generic, arithmetic, floating_point };
template <container_type, typename T>
struct container_base {                   // generic
//...
};
template <typename T>
struct container_base<arithmetic,T> {     // replaces container_integral_base
//...
};
template <typename T>
struct container_base<floating_point,T> { // replaces container_floating_point_base
//...
};

仍然没有名字,但我会考虑用另一个未命名的更常见的模式替换您的未命名模式,您可以简要地将其描述为从专业化

继承的