template <typename>
struct B
{
constexpr static int T = 5;
};
template <int T>
struct D : B<int>
{
constexpr static int value = T;
};
int main()
{
std::cout << D<7>::value << std::endl; // 5, how to get 7 ?
}
Demo
As I have recently learned that the template parameters of a template derived class get checked after the names in the base class during lookup. That being said, is there anyway to qualify the name T
initializing value
to refer to the template parameter T
of the derived class?
EDIT:
So far from discussions in the comments it seems that the only way to achieve this is by making the base class type/value dependent which will delay the lookup to the names of the base (to the instantiation phase) and thus making the only available value for T is the template parameter.
Inheritance provides runtime abstraction. Templates are code generation tools. Because the concepts are orthogonal, they may happily be used together to work towards a common goal.
Template classes and functions can make use of another kind of template parameter known as a non-type parameter. A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument.
It is possible to inherit from a template class. All the usual rules for inheritance and polymorphism apply. If we want the new, derived class to be generic it should also be a template class; and pass its template parameter along to the base class.
A template argument for a template template parameter is the name of a class template. When the compiler tries to find a template to match the template template argument, it only considers primary class templates. (A primary template is the template that is being specialized.)
I'm not entirely sure I understand the question but I think decltype
does what you want:
template <int T>
struct D : B<decltype(T)>
{
constexpr static decltype(T) value = T;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With