Curiously recurring template pattern (CRTP) with static constexpr in Clang

做~自己de王妃 提交于 2019-12-21 04:21:14

问题


Consider my simple example below:

#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;
}

In g++, this compiles fine and prints 5 as expected. In Clang, however, it fails to compile with the error no member named 'x' in 'Derived'. As far as I can tell this is correct code. Is there something wrong with what I am doing, and if not, is there a way to have this work in Clang?


回答1:


As linked in the comments, Initializing a static constexpr data member of the base class by using a static constexpr data member of the derived class suggests that clang behaviour is standard conformant up to C++14 here. Starting with Clang 3.9, your code compiles successfully with -std=c++1z. An easy possible workaround is to use constexpr functions instead of values:

#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;
}



回答2:


This probably isn't the answer anyone would be looking for, but I solved the problem by adding a third class:

#include <iostream>

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

class Data
{
public:
     static constexpr int x = 5;
};

class Derived : public Base<Data>, public Data {};

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

It works as desired, but unfortunately it doesn't really have the benefits of CRTP!



来源:https://stackoverflow.com/questions/35854686/curiously-recurring-template-pattern-crtp-with-static-constexpr-in-clang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!