c++ - 在同一类中使用 constexpr 作为模板参数时出错

标签 c++ compiler-errors c++11 constexpr

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

template<int n> struct foo { };

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

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

对于 gcc 4.6.1,错误信息是:

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,错误信息是:

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 上给出相同的错误消息:

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标准的哪些条款说错了?

最佳答案

在 C++ 中,类的成员函数的内联定义仅在类中的每个声明都被解析后才被解析。因此,在您的第一个示例中,编译器无法在声明 function() 的位置看到 number() 的定义。

(没有已发布的 clang 版本支持评估 constexpr 函数,因此您的所有测试用例都不能在那里工作。)

关于c++ - 在同一类中使用 constexpr 作为模板参数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8108314/

相关文章:

c++ - Printf %X 标识符 - 指针的奇怪行为

与 C# 表达式一起使用时,ASP.NET 表达式 <%= ...%> 给出错误 CS 1518

c++ - 获取模板函数类型

c++ - 如何在 C++ 中创建 Barrier?

c++ - 在gem5中的文件中打印所有cache_blocks

c++ - 如何忽略 boost::regex_search() 函数中的反斜杠字符?

c++ - 在参数列表中重复使用变量时前缀增量变量

gcc - 为 ARM 交叉编译 zlib

c++ - 初始化静态成员使编译工作......但是为什么

c++ - 调用了错误的构造函数