将CRTP与static_assert一起使用时的编译器错误

托特

考虑以下代码:

template<typename Derived>
struct Base {
    static constexpr int x_base = Derived::x_derived;
    //static_assert(x_base > 1, "Oops");
};

struct Derived : public Base<Derived> {
    static  constexpr int x_derived = 5 ;
};

Base<Derived> obj;

这在gcc上编译正常,但是如果我取消注释该static_assert行,它会抱怨

error: incomplete type 'Derived' used in nested name specifier
static constexpr int x_base = Derived::x_derived;

我尝试了从4.9到5.3的不同版本的gcc,但遇到了相同的错误(您可以在这里的godbolt上尝试)。clang即使没有也不拒绝编译它static_assert,并抱怨说

error: no member named 'x_derived' in 'Derived'
static constexpr int x_base = Derived::x_derived;

哪个编译器正确(如果有)?有修复代码的好方法吗?

巴里

访问嵌套名称要求该类是完整的,但Derived在这里还不完整:

template<typename Derived>
struct Base {
    static constexpr int x_base = Derived::x_derived;
                                  ^^^^^^^^^
};

因此代码格式错误。

有一些解决方法。首先,您可以单独将值作为模板参数传入:

template <typename Derived, int x_derived>
struct Base {
    static constexpr int x_base = x_derived;
};

struct Derived : public Base<Derived, 5> { };

其次,如果可能的话(例如,您不需要x_derived声明任何成员),可以将值移到函数中以延迟其实例化:

template<typename Derived>
struct Base {
    static constexpr int x_base() {
        static_assert(Derived::x_derived > 1, "Oops");
        return Derived::x_derived;
    }

};

struct Derived : public Base<Derived> {
    static constexpr int x_derived = 5;
};

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将MySQL连接器与Python一起使用时SSL连接错误

为什么Java编译器会抱怨将foreach与原始类型一起使用?

为什么在eclipse中编译相同的代码,然后通过ant与eclipse编译器一起使用时,类文件的大小不同?

我如何将JDK编译器与Dr Java一起使用,而不是Eclipse编译器?

如何检测编译器是否支持static_assert?

无法将Enumerable.Count与List一起使用,编译器假定为List.Count

将@Transactional与传播属性一起使用时发生编译错误

无法在类范围内将`static_assert`与`sizeof`一起使用(但方法范围还可以)

static_assert和Intel C ++编译器

编译器错误:“错误CS0307:变量'int'不能与类型参数一起使用”

与转换运算符一起使用时,编译器为什么不能推断出模板参数?

将config.json文件与BBC Micro:bit Mbed在线编译器一起使用

将QT Creator 5.8与MSVC 2015编译器一起使用

在C ++中将g ++和Visual Studio 14 2015编译器与regex一起使用时会得到不同的结果

如果constexpr在lambda中带有static_assert,哪个编译器正确?

将gcc插件与交叉编译器一起使用,未定义符号

将filter_map与易错的映射功能一起使用时,如何汇总错误的迭代器?

将pynput与pyinstaller一起使用时出现错误

将单例与泛型和complementHandler一起使用时发生编译错误

将空隙彼此放在一起时出错(&编译器无法编写代码)

与命名空间System.Collections一起使用时,IEnumerable报告编译器错误

将gcc_shared与构造函数一起使用时,gcc 4.7.3内部编译器错误

将数组用作映射键不能与C ++ 11编译器命令一起使用吗?

将32位DLL与64位Lazarus编译器一起使用

将FreeRTOS与XC8编译器一起使用

将Wordpress与jetPack插件一起使用时LEMP服务器上的403错误

static_assert(std :: is_abstract)在Visual Studio 2013中导致编译器错误

将 Quadprog++ 与 Eigen 一起使用时的 C++ 编译错误

是否可以将 Clang libtooling 与其他编译器一起使用?