How to make a template-dependent typedef more convenient?

时间:2015-05-08 09:58:16

标签: c++ templates typedef

I have several classes with all the same template arguments. They use private void Result_Load(object sender, EventArgs e) { System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Green); System.Drawing.Graphics formGraphics = this.CreateGraphics(); formGraphics.FillRectangle(myBrush, new Rectangle(0, 0, 200,300)); myBrush.Dispose(); formGraphics.Dispose(); } which is also a template. So I File f = new File("/Users/pavankumar/Desktop/Testing/Java.txt"); f.createNewFile(); it to OftenUsedType to have more convenient notation:

typedef

Unfortunately, I have to do this in all classes which use R, since it depends on the template parameters.

The only way to make this a bit more convenient is to do the template <class T, int A, int B> class Obj{ typedef OftenUsedType<T, A, B> R; } in a class and inherit it to all classes which use it:

OftenUsedType

But I still have to inherit the typedef class into all classes which use the type...

Is there a more convenient, good-style way to do it?

2 个答案:

答案 0 :(得分:2)

If C++11 is acceptable, you could use an alias template, which has a much more natural syntax:

generate

答案 1 :(得分:1)

我要做的第一件事就是将您的int Aint B替换为

template<int I>
using int_t = std::integral_constant<int, I>;

以便所有模板都是类型。您可以constexpr构建并使用constexpr operator()来获取整数的值。

template<class T>struct tag{using type=T;};
template<class Tag>using type=typename Tag::type;

template<template<class...>class Z, class T>
struct transcribe;

template<template<class...>class Z, template<class...>class T, class...Ts>
struct transcribe<Z,T<Ts...>>:tag<Z<Ts...>> {};

template<template<class...>class Z, class T>
using transcribe_t = type<transcribe<Z,T>>;

transcribe获取模板和其他模板的实例,并将第二个实例模板的参数转录到第一个模板中,并返回结果。然后我们利用它来提取封闭类的参数,并从中创建OftenUsedType

template<class T>
using often = transcribe_t< OftenUsedType, T >;

现在:

template<class T, class iA, class iB>
class Obj {
  using R = often<Obj>;
};

将导致often<Obj>成为OftenUsedType<T,iA,iB>using是可选的 - 您可以在often<Obj>Obj获得OftenUsedType<T,iA,iB>

这可以在不将所有模板参数转换为类的情况下完成。它只需要一个不同的(和更丑陋的)转录:

template<template<class, int, int>class Z, class T>
struct transcribe;
template<template<class, int, int>class Z,
  template<class, int, int>class T,
  class X, int A, int B>
struct transcribe<Z, T<X,A,B>>:tag<Z<X,A,B>> {};
template<template<class, int, int>class Z, class T>
using transcribe_t=type<transcribe<Z,T>>;

必须为每种类型/标量的模式进行手工编码。这让我很伤心。