这种继承的编译时确定模式是否有名称?

时间:2013-07-12 22:08:55

标签: c++ design-patterns inheritance c++11 template-meta-programming

最近,我一直在开发一个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 */ };

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

1 个答案:

答案 0 :(得分:2)

我认为我之前没有看到过与变参数模板一起使用的模式,尽管在多个库中可以看到与专业化一起使用的类似方法:

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
//...
};

仍然没有它的名字,但我会考虑用另一个未命名的更常见的模式替换你的未命名模式,你可以简洁地描述为继承专业化