Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't typename template parameters implicitly recognized as types?

Very often in C++ class definitions, especially in libraries, trait class etc., you see code similar to the following snippet:

template <typename Bar, typename Baz>
class Foo {
    using bar_type = Bar;
    using baz_type = Baz;
    // ... etc.
}

And only with these lines can you later refer to Foo<A,B>::bar_type or Foo<C,D>:baz_type. I'm wondering: Why doesn't the language standard require the compiler to automatically define types using the typename template parameters, i.e. allow removing the two using lines, and recognize Foo<A,B>::Bar as A and Foo<C,D>::Baz as D?

This should not even break existing code, since within Foo, the identifiers Bar and Baz are already taken anyway.

like image 760
einpoklum Avatar asked May 25 '16 22:05

einpoklum


1 Answers

Parameter names aren't part of the entity that's being declared. This is true for both functions and templates. The following code only declares two separate entities:

extern void f(int, char, bool);
extern void f(int a, char b, bool c);
extern void f(int x, char b, bool z);

template <typename> struct X;
template <typename A> struct X;
template <typename T> struct X;

Note in particular that the following code is perfectly fine:

template <typename T> struct X { void f(); };   // X<T>::f not yet defined
template <typename U> void X<U>::f() {}         // now it's defined

All attempts at deriving additional structure from parameter names must deal with this situation. One of the most popular requests in this area are named function parameters; to date there has not been a satisfactory proposal for such an extension.

To some extent, all such proposals would require making the parameter names part of the declared entity. For functions, for example, that would raise the question whether parameter names would need to be mangled and exposed to the linker.

like image 186
Kerrek SB Avatar answered Dec 19 '22 20:12

Kerrek SB