Is it possible to access values of non-type template parameters in specialized template class?
If I have template class with specialization:
template <int major, int minor> struct A {
void f() { cout << major << endl; }
}
template <> struct A<4,0> {
void f() { cout << ??? << endl; }
}
I know it the above case it is simple to hardcode values 4 and 0 instead of using variables but what I have a larger class that I'm specializing and I would like to be able to access the values.
Is it possible in A<4,0> to access major
and minor
values (4 and 0)? Or do I have to assign them on template instantiation as constants:
template <> struct A<4,0> {
static const int major = 4;
static const int minor = 0;
...
}
No, you don't have access to the specialized non-type template parameters. But here is a way to not repeat yourself in the implementation of
f
:For this example, one doesn't gain all too much, as one needs to write the
4,0
twice (--so you could write it as well a second time in thecout
in your OP). But it starts to pay out if you have more functions using the template parameters.Not really an answer to your question, but the idea below helped me once:
Not really an answer to your question, but you could enumerate them, viz:
This kind of problem can be solved by having a separate set of "Traits" structs.