Error using a constexpr as a template parameter within the same class

血红的双手。 提交于 2019-11-26 21:51:18

问题


If I try to compile the following C++0x code, I get an error:

template<int n> struct foo { };

struct bar {
    static constexpr int number() { return 256; }

    void function(foo<number()> &);
};

With gcc 4.6.1, the error message is:

test.cc:6:27: error: ‘static constexpr int bar::number()’ used before its definition
test.cc:6:28: note: in template argument for type ‘int’

With clang 2.8, the error message is:

test.cc:6:20: error: non-type template argument of type 'int' is not an integral
      constant expression
        void function(foo<number()> &);
                          ^~~~~~~~
1 error generated.

If I move the constexpr function to a base class, it works on gcc, and gives the same error message on clang:

template<int n> struct foo { };

struct base {
    static constexpr int number() { return 256; }
};

struct bar : base {
    void function(foo<number()> &);
};

Is the code wrong, or is it a limitation or bug on gcc 4.6's implementation of C++0x? If the code is wrong, why is it wrong, and which clauses of the C++11 standard say it is incorrect?


回答1:


In C++, inline definitions of member functions for a class are only parsed after every declaration in the class is parsed. Therefore, in your first example, the compiler can't see the definition of number() at the point where function() is declared.

(No released version of clang has support for evaluating constexpr functions, so none of your testcases will work there.)




回答2:


I've got a simillar error with the following code:

struct Test{
     struct Sub{constexpr Sub(int i){}};
    static constexpr Sub s=0;
};

"error: 'constexpr Test::Sub::Sub(int)' called in a constant expression" on gcc 4.7.1. while This will compile successfully:

struct Sub{constexpr Sub(int i){}};
struct Test{
    static constexpr Sub s=0;
};


来源:https://stackoverflow.com/questions/8108314/error-using-a-constexpr-as-a-template-parameter-within-the-same-class

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