使用constexpr作为同一类中的模板参数时出错 [英] Error using a constexpr as a template parameter within the same class

查看:477
本文介绍了使用constexpr作为同一类中的模板参数时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我尝试编译以下C ++ 0x代码,我会收到一个错误:

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()> &);
};

使用gcc 4.6.1时,错误消息是:

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’

对于clang 2.8,错误消息是: / p>

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.

如果我将 constexpr 基类,它适用于gcc,并在clang上提供相同的错误消息:

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()> &);
};

代码错误,或者是gcc 4.6执行C + + 0x?如果代码是错误的,为什么是错误的,C ++ 11标准的哪些子句说它是不正确的?

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?

推荐答案

在C ++中,类的成员函数的内联定义只有在类中的每个声明都被解析之后才被解析。因此,在第一个例子中,编译器在 function() number()的定义

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.

(没有发布版本的clang支持评估constexpr函数,所以你的测试用例都不会在那里工作。)

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

这篇关于使用constexpr作为同一类中的模板参数时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆