考虑我下面的简单示例:
#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/