Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template inheritance hides template parameters

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.

like image 578
mkmostafa Avatar asked Jun 01 '18 08:06

mkmostafa


People also ask

Is inheritance better than templates?

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.

Can we pass Nontype parameters to templates?

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.

Can template functions be inherited?

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.

Can a template be a template parameter?

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.)


1 Answers

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;
};
like image 166
Alan Birtles Avatar answered Oct 20 '22 01:10

Alan Birtles