4

I would like to access a template parameter outside of a class. I usually do this as follows:

template <class T>
class A
{
  typedef typename T T;
}

A<int>::T;

I would like to be able to do the same for non-type template parameters. This doesn't work:

template <int T>
class A
{
  typedef typename T T;
}

A<3>::T;

I will clarify why I need this. I want to define a second class as follows:

template <class C>
class B
{
  static int func() {return C::T;}
}

B<A<3> >::func();

What is the correct way to do this? Thank you very much.

Benjy Kessler
  • 7,356
  • 6
  • 41
  • 69

3 Answers3

5

That's because T is not a type name and you cannot typedef it. It is an int value and, if you want to access it as a static member of the class, you need a static member int. Seems like what you really want is this:

template <int T>
class A
{
  public:
    static const int x = T;
};

doSomething(A<5>::x);
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
2

It's a value, and not a type, so perhaps:

template <int T>
class A
{
  static const int param = T;
};

And then you can access it as A<42>::param. Not that it helps much, unless A is itself used as a template parameter somewhere else.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
1

in the second case, T is not a type, it's an int value. Therefore you should define it as a const int or static const int value.

template <int T>
class A {
    static const int T = T;
};

Note that it is customary to use T for types (in particular when the template is monadic, since there is no ambiguity on the type), and other names for constants, usually a more meaningful name, for instance SIZE or preferably Size (all caps symbols are best used for macros).

template <int Param>
class A {
    static const int param = Param;
};

See other SO questions (like this one) for the use of static const values in the context of a template definition.

Community
  • 1
  • 1
didierc
  • 14,572
  • 3
  • 32
  • 52