C++ Logo

std-proposals

Advanced search

[std-proposals] Make typename optional when used with a name dependent on a constrained template

From: Christoph Meyer <christoph.meyer.2006_at_[hidden]>
Date: Tue, 21 Feb 2023 22:27:57 +0100
[using markdown]
Hello,

this very first draft of the proposal is about making the `typename`
keyword optional when used together with a name that is dependent on a
constrained template whose constraints guarantee that the dependent
name is indeed a typename.

Explanation
===========
Please consider the following example:
```c++
template <typename T>
concept has_inner_type = requires
{
    typename T::inner;
};

template <typename BaseType>
struct my_pointer
{
    typedef BaseType* inner;
};

template <has_inner_type T>
void foo(T value)
{
    typename T::inner innerValue;
    // do something with value and innerValue
}

int main(void)
{
    my_pointer<int> p;
    foo(p);
    return 0;
}
```

The type requirement `typename T::inner;` ensures that the name
`inner` dependent on any type `T` that matches said requirement is
always a type and not a value, technically making the keyword
`typename` obsolete in that context.

The function `foo` would then read like this:
```c++
template <has_inner_type T>
void foo(T value)
{
    T::inner innerValue;
    // do something with value and innerValue
}
```

Motivation
==========
The whole idea behind type template parameters is to generalize
functions, classes, structs or variables by giving the programmer the
possibility to swap out a type template parameter with a variety of
types. In most cases, it is possible to use type template parameters
*as if* they were real types and actually swapping type template
parameters with actual types (like with macros) would result in valid
code, which in my opinion feels natural and matches most programmers'
way of thinking about templates.

Making the `typename` keyword optional as describes above would bring
us a step closer to being able to use a type template parameter like a
real type.


Please let me know your opinions on this proposal, and please excuse
possible formal or linguistic errors, as this is my first proposal and
I do not speak English as a native language.

Sincerely,
Christoph Meyer

Received on 2023-02-21 21:28:00