c ++模板不止一个原型

时间:2013-12-27 20:53:17

标签: c++ templates

我有一个相对复杂的模板,有很多参数(大多数都带有默认值)。例如:

template <typename I,
          typename S = BasicS<I>,
          typename C = BasicC<I>,
          typename E = BasicE<I> >
class Foo ...

不幸的是,无论我选择什么参数的顺序,总会有一些情况,你可能只想改变最后一个。

如何为同一模板创建更多原型,比如说

template <typename I,
          typename E>
class Foo1 : Foo<I, BasicS<I>, BasicC<I>, E >
{
    ... redefine the constructors
};

但没有继承以避免重新定义构造函数

3 个答案:

答案 0 :(得分:4)

您可以使用C++11's template aliases

实现这一目标
template <typename I, typename E>
using Foo1 = Foo<I, BasicS<I>, BasicC<I>, E>;

答案 1 :(得分:2)

假设(根据你的评论)你不能使用C ++ 11,你可以使用嵌套的typedef:

template <typename I, typename E>
struct Foo1 {
  typedef Foo<I, BasicS<I>, BasicC<I>, E> type;
};

template <typename I, typename C>
struct Foo2 {
  typedef Foo<I, BasicS<I>, C> type;
};

然后会像这样使用:

Foo1<MyI, MyE>::type myFoo;

当然,您也可以将原始Foo重命名为GenericFoo或其他内容,并为其提供带有typedef的Foo结构,以便您提供一致的界面。

答案 2 :(得分:0)

假设您可以接受不同的名称,则可以使用using别名:

template <typename I, typename E>
using Foo1 = Foo<I, BasicS<I>, BasicC<I>, E>;