Reputation: 7656
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.
Upvotes: 4
Views: 367
Reputation: 14750
in the second case, T
is not a type, it's an int
value. Therefore you should define it as a const int
orstatic 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.
Upvotes: 1
Reputation: 92371
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.
Upvotes: 2
Reputation: 110758
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);
Upvotes: 5