c++ - 是否可以像在其他编译器中的 Microsoft C 中那样使用类型化名称或类型名称来声明构造函数?

标签 c++ c++14

很烦人,它似乎在 Microsoft C 中工作,但在我使用的其他编译器中却不工作。

在使用模板时特别理想。也许我不知道执行此操作的“符合标准的方式”,但它确实很有用,我希望代码可以在 gcc、clang 等平台上编译。

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... /* messy */ >
{
public:
    SubClass(int arg, blah, blah) : SimplerName(arg) { ... }
}.

我在使用 gcc 和 emscripten 时遇到严重的问题

In file included from /home/peterk/didi-wasmtest/build/include/artd/Matrix4Base.h:2:
    /home/peterk/didi-wasmtest/build/include/artd/../../../artdlib-cpp/vecmath/Matrix4Base.h:91:21: error: expected member name or ';' after declaration specifiers
    inline Matrix4Base() {
        ~~~~~~~~~~~~~~~~~~ ^

header中的代码

template<class Real, class Super>
class ARTD_API_ARTD_VECMATH Matrix4ColumnMajorT
    : public Matrix4CommonT<Real, Super>
{
public:
    typedef Matrix4ColumnMajorT<Real, Super> Matrix4Base;
protected:
    inline Matrix4Base() {
        SType().setIdentity();
    }
    inline Matrix4Base(bool asIdentity) {
        if (asIdentity) SType().setIdentity();
    }
    inline Matrix4Base(const Super &src) {
        SType().set(src);
    }
public:
... 
};

这一切都在 Microsoft C 上编译和运行,但在基于 gcc 和 clang 的编译器上使用 typedef 名称 barf 声明的所有构造函数。

我尝试使用它的地方是我根据宏选择哪个基类,但希望子类不必声明两组构造函数或使用宏来定义它们。我尝试了有和没有模板参数的变体。似乎需要模板参数。此代码从 visual studio 2017 在 MSC 上编译并生成正确的代码,但我的主要目标是 gcc 和 emscripten ( clang )

class ARTD_API_ARTD_VECMATH Matrix4f
#ifdef Matrix4f_RowMajor
    : public Matrix4RowMajorT<float, Matrix4f>
#else
    : public Matrix4ColumnMajorT<float, Matrix4f>
#endif
{
public:

    Matrix4f() : Matrix4Base()
    {}
    Matrix4f(bool asIdentity) : Matrix4Base(asIdentity)
    {}
    Matrix4f(const Matrix4f &src) : Matrix4Base(src)
    {}

最佳答案

模板名称用作类模板本身范围内的注入(inject)类名称。这是标准且有效的:

template<class T, class T1, ... /* messy, verbose */ >
class MyTemplate {
protected:
    typedef MyTemplate SimplerName;

    // declare a constructor
    MyTemplate (int arg) { ... }
};

Live example

您甚至不需要子类的别名:

class SubClass
    : public MyTemplate<int, char, bool /* messy */ >
{
public:
    SubClass(int arg) : MyTemplate(arg) {  }
};

Live example

关于c++ - 是否可以像在其他编译器中的 Microsoft C 中那样使用类型化名称或类型名称来声明构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53690328/

相关文章:

c++ - QtCreator错误: QGroupBox: No such file or directory

c++ - 如何对齐控制台输出的数字在同一位置

c++ - std::move weak_ptr::lock 的返回值弄乱了 shared_ptr 的引用计数?

c++ - 用spirit x3解析递归规则

C++ 使用较新编译器的功能生成代码以供较旧编译器使用

c++ - 选择正确的子类以编程方式实例化

C++ gsoap mime/dime 用于 Windows 中的二进制文件

c++ - 有效的双向作用域枚举映射

c++ - 在支持 11 的机器上最高 D3D_FEATURE_LEVEL 是 9.3

c++ - 如何让现在的编码结构更加灵活