首页 文章

typedef名称可以用于声明或定义构造函数吗?

提问于
浏览
14

Standardese:

[class.ctor] 12.1 / 1说

特殊的声明符语法用于声明或定义构造函数 . 语法使用: - 一个可选的decl-specifier-seq,其中每个decl-specifier都是一个函数说明符或constexpr, - 构造函数的类名,以及 - 该顺序的参数列表 .

[class.name] 9.1 / 4说

命名类类型或其cv限定版本的typedef-name(7.1.3)也是类名 . 如果在需要类名的地方使用了命名cv限定类类型的typedef-name,则忽略cv限定符 . typedef-name不得用作class-head中的标识符 .

另外[expr.prim.general] 5.1.1 / 8说

如果使用class-name :: class-name,并且两个类名称引用同一个类,则此表示法命名构造函数(12.1) .


申请:

在我看来,应该允许使用typedef名称来声明构造函数(尽管事实上12.1 / 1不使用斜体类名) .

例如,给定:

struct Foo;
typedef Foo Bar;

然后

struct Foo { Bar() {} }; // defines Foo's constructor. - 1

或者代之以

struct Foo;
struct Foo { Foo() };
typedef Foo Bar;

然后

Foo::Bar() {}; // defines Foo's constructor - 2

要么

Bar::Bar() {}; // defines Foo's constructor - 3

要么

Bar::Foo() {}; // defines Foo's constructor - 4

任何这些都应该是合法的 . 然而,似乎没有人接受定义2或3,MSVC接受1,MSVC,clang和gcc都接受4 .

我的分析是否正确,所有这些编译器都错了吗?

2 回答

  • 14

    §12.1/ 3的the working draft N3337 (Feb 2012)

    typedef-name不能用作构造函数声明的declarator-id中的类名 .

    这排除了(1) .

    §12.1/ 1似乎对声明和定义使用术语“声明”:

    特殊的声明符语法用于声明或定义构造函数 . [......]在这样的声明中,[...]

    (没有明确提及“定义”) . 我认为这是否适用于类外定义或仅适用于内联定义有点不清楚 . 如果它适用于所有类型的定义,这也将排除(2)和(3) . (4)在任何情况下都应合法 .

  • 0

    好吧,它似乎在Microsoft C中工作,但不是我使用的其他编译器 . 特别是在模板中需要时 . 也许我不知道“符合标准的方式”,但它在模板中非常有用 .

    template<class T, class T1, ... /* messy, verbose */ >
    class MyTemplate {
    protected:
        typedef MyTemplate<T,T1, ... /* messy, verbose */ > SimplerName;
    
        // declare a constructor
        SimplerName(int arg) { ... }
    };
    class SubClass
        : public MyTemplate<x,y....>
    {
    public:
        SubClass(int arg) : SimplerName(arg) { ... }
    }.
    

    也许另一个问题也许这在GCC,Clang等中不起作用,有没有办法在其他编译器中做到这一点?

相关问题