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

发布于 2024-12-14 21:38:31 字数 1022 浏览 2 评论 0原文

如果我尝试编译以下 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 标准的哪些条款说它不正确?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

平安喜乐 2024-12-21 21:38:31

在 C++ 中,类的成员函数的内联定义仅在解析类中的每个声明后才会进行解析。因此,在第一个示例中,编译器在声明 function() 时看不到 number() 的定义。

(clang 的任何发布版本都不支持评估 constexpr 函数,因此您的任何测试用例都无法在那里工作。)

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.)

拿命拼未来 2024-12-21 21:38:31

这将编译成功:

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

This will compile successfully:

struct Sub{constexpr Sub(int i){}};
struct Test{
    static constexpr Sub s=0;
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文