Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can templated aliases of anonymous struct/class-es not be defined directly?

I can create the following:

using Foo = struct { /*Implementation*/ };

template<class>
using Bar = Foo;

However the following is not allowed:

template<class>
using Bar = struct { /*Implementation*/ };

The error from Clang is more helpful than GCC, and states:

error: '(anonymous struct at file:line:column)' cannot be defined in a type alias template


Any reasons why the second code example is not allowed?

Note:

  • Please state any examples for which the second code example (if allowed) may cause problems with the language.

  • Any citation from the standard is also helpful.

like image 854
Anirban Sarkar Avatar asked Apr 27 '19 07:04

Anirban Sarkar


1 Answers

Defining a class or an enumeration in an alias-declaration that is part of a template alias is forbidden by [dcl.typedef]/2:

A typedef-name can also be introduced by an alias-declaration.

...

The defining-type-specifier-seq of the defining-type-id shall not define a class or enumeration if the alias-declaration is the declaration of a template-declaration.

The latter was introduced as CWG issue 1159 was accepted, as part of FCD N3092.

The comments and proposed resolution of the associated N3092 comment US 74 does provide some rationale as to why this restriction was introduced [emphasis mine]:

Comment (ID) US 74

Comment

An alias-declaration allows a class or enumeration type to be defined in its type-id (7.1.6p3). However, it's not clear that this is desirable when the alias-declaration is part of a template alias:

template<typename T> using A =
struct { void f(T) { } };

Proposed resolution

Either prohibit the definition of classes and enumerations in template aliases, or prohibit the use of template parameters in such definitions, or add an example illustrating this usage.

Owner & issue

CWG 1159

Disposition

ACCEPTED

Definition of a class or enumeration is now prohibited in a template alias.

It would seem as if no one protested (convincingly enough) to prohibiting the definition of classes and enumerations in template aliases, implying that it's likely that no one was able to give a convincing example illustrating where this would be useful.

like image 54
dfrib Avatar answered Oct 29 '22 23:10

dfrib