以下の内容はhttps://yohhoy.hatenadiary.jp/entry/20260308/p1より取得しました。


冗長なtypenameキーワード

プログラミング言語C++において型(type)名を記述するとき、C++11以降では修飾名(qualified name)に限って冗長なtypenameキーワードを記述しても良い。

#include <cstddef>
using std::size_t;
struct S { using type = int; };

typename int x0;     // NG
typename size_t n0;  // NG

typename std::size_t n1;  // OK
typename ::size_t n2;     // OK
typename S::type v1;      // OK

C++03時点ではtypenameキーワードの明記はテンプレート定義内に限定されていたが、Core Working Group Issue#382により修正された経緯がある。同Issueより一部引用(下線部は強調)。

P. J. Plauger, among others, has noted that typename is hard to use, because in a given context it's either required or forbidden, and it's often hard to tell which. It would make life easier for programmers if typename could be allowed in places where it is not required, e.g., outside of templates

Notes from the April 2003 meeting:
There was unanimity on relaxing this requirement on typename. The question was how much to relax it. Everyone agreed on allowing it on all qualified names, which is an easy fix (no syntax change required). But should it be allowed other places? P. J. Plauger said he'd like to see it allowed anywhere a type name is allowed, and that it could actually be a decades-late assist for the infamous "the ice is thin here" typedef problem noted in K&R I.

Notes from October 2003 meeting:
We considered whether typename should be allowed in more places, and decided we only wanted to allow it in qualified names (for now at least).

おまけ:CWG 382で言及される “typedef problem” に関して、K&R C 1st Ed., §11.1 Lexical scopeより言及箇所を引用する。C言語では「変数名のない空の宣言*1」が許容されることと、「型名省略時の暗黙int宣言」はC99で削除されたため、現在からみると意図を読み取りづらい。

In all cases, however, if an identifier is explicitly declared at the head of a block, including the block constituting a function, any declaration of that identifier outside the block is suspended until the end of the block.

Remember also (§8.5) that identifiers associated with ordinary variables on the one hand and those associated with structure and union members and tags on the other form two disjoint classes which do not conflict. Members and tags follow the same scope rules as other identifiers. typedef names are in the same class as ordinary identifiers. They may be redeclared in inner blocks, but an explicit type must be given in the inner declaration:

typedef float distance;
...
{
    auto int distance;
    ...

The int must be present in the second declaration, or it would be taken to be a declaration with no declarators and type distance.

脚注† lt is agreed that the ice is thin here.

関連URL

*1:GCCでは警告"useless type name in empty declaration"、Clangでは警告"declaration does not declare anything"として検知される。




以上の内容はhttps://yohhoy.hatenadiary.jp/entry/20260308/p1より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14