Alex Coplan
Alex Coplan

Reputation: 13371

Making `using` declaration inside template before class declaration

Say I have the following code:

template<typename X, typename Y, typename Z>
class Foo : public Parent<SomeComplicatedExpressionInvolving<X,Y,Z>> {
  using Useful = SomeComplicatedExpressionInvolving<X,Y,Z>;

  Useful member;
  Useful another_member;
  Useful f(Useful x) { return x; } // etc.
};

The Useful declaration is useful here because it allows us to write Useful in place of some really long expression.

Is it possible to neaten this further and put the using declaration before the class declaration? Obviously, the following code doesn't compile:

template<typename X, typename Y, typename Z>
using Useful = SomeComplicatedExpressionInvolving<X,Y,Z>
class Foo : public Parent<Useful> {      
  Useful member;
  Useful another_member;
  Useful f(Useful x) { return x; } // etc.
};

but is there a way to write something to this effect? It may be useful to make multiple using declarations in this way (i.e. within the template scope but before a class declaration).

Upvotes: 2

Views: 133

Answers (2)

max66
max66

Reputation: 66210

I don't think it's a good idea (+1 for the AndyG's solution) but... just for fun... you can use a template type with default value instead of using.

By example

template <typename, typename, typename>
struct SomeComplicatedExpressionInvolving
 { };

template <typename>
struct Parent
 { };

template <typename X, typename Y, typename Z,
          typename Useful = Parent<SomeComplicatedExpressionInvolving<X,Y,Z>>>
class Foo : public Useful
 {
   Useful member;
   Useful another_member;
   Useful f(Useful x) { return x; } // etc.
 };

int main ()
 {
   Foo<int, long, int> f;
 }

Upvotes: 3

AndyG
AndyG

Reputation: 41100

You cannot have a using defined after the template and before the class. However, You could clean up what you do have a little bit with two using type aliases

template<typename X, typename Y, typename Z>
using Useful_t = SomeComplicatedExpressionInvolving<X,Y,Z>;

template<class X, class Y, class Z>
class Foo : public Parent<Useful_t<X, Y, Z>> {
  using Useful = Useful_t<X, Y, Z>;
  Useful member;
  Useful another_member;
  Useful f(Useful x) { return x; } // etc.
};

Live Demo

Upvotes: 2

Related Questions