c++ - Clang 中带有静态 constexpr 的奇怪的循环模板模式 (CRTP)

标签 c++ templates c++11 clang crtp

考虑我下面的简单示例:

#include <iostream>

template <typename T>
class Base
{
public:
    static constexpr int y = T::x;
};

class Derived : public Base<Derived>
{
public:
    static constexpr int x = 5;
};


int main()
{
    std::cout << Derived::y << std::endl;
}

在 g++ 中,这可以正常编译并按预期打印 5。然而,在 Clang 中,它无法编译并出现错误 no member named 'x' in 'Derived'。据我所知这是正确的代码。我正在做的事情有问题吗?如果没有,是否有办法在 Clang 中完成这项工作?

最佳答案

如评论中所链接,Initializing a static constexpr data member of the base class by using a static constexpr data member of the derived class表明 clang 行为在此处符合 C++14 的标准。从 Clang 3.9 开始,您的代码可以使用 -std=c++1z 成功编译。 一个简单的解决方法是使用 constexpr 函数而不是值:

#include <iostream>

template <typename T>
class Base
{
public:
    static constexpr int y() {return T::x();}
};

class Derived : public Base<Derived>
{
public:
    static constexpr int x() {return 5;}
};

int main()
{
    std::cout << Derived::y() << std::endl;
}

关于c++ - Clang 中带有静态 constexpr 的奇怪的循环模板模式 (CRTP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35854686/

相关文章:

c++ - 确定一组点是在正方形内部还是外部

c++ - 修改函数中的指针值

c++ - C++排序自适应函数

c++ - 在给定模板参数的模板类类型的类中声明变量

c++ - Boost 文件系统与 c++11 线程不兼容

c++ - Boost元组和STL vector 编译错误

c++ - 复制构造函数或=运算符?

c++ - 将模板类本身定义为一个类型

c++ - 使用 std::function 的优点

c++ - 如何解决 ‘std::list<int>*’ 到 ‘std::list<int> [0]’ 分配中的不兼容类型?