使用引用的constexpr静态成员作为模板参数 [英] Using a constexpr static member of a reference as template argument

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

问题描述

我试图弄清楚是GCC还是Clang对C ++ 17标准的解释不同/错误.

I'm trying to figure out whether GCC or Clang interpret the C++17 standard differently / wrong here.

这是我的代码,使用GCC 8进行编译,但不使用Clang 6:

This is my code, which does compile using GCC 8, but not using Clang 6:

struct BoolHolder {
    constexpr static bool b = true;
};

template<bool b>
class Foo {};

int main() {
    BoolHolder b;
    Foo<b.b> f; // Works

    BoolHolder & br = b;
    Foo<br.b> f2; // Doesn't work
}

我想知道为什么会这样.显然,b.b是有效的constexpr(或第一个Foo<b.b>无效). br.b不是有效的constexpr吗?为什么?对象或引用本身应该与它无关,因为我们在这里访问静态constexpr成员,对吧?

I wonder why that is. Obviously, b.b is a valid constexpr (or the first Foo<b.b> wouldn't be valid). Is br.b not a valid constexpr? Why? The object or the reference itself should have nothing to do with it, since we're accessing a static constexpr member here, right?

如果这实际上不是有效的C ++ 17,那么即使GCC都没有警告我(即使我启用了-Wall -Wextra -pedantic)这一事实,也应该被视为错误吗?

If this is really not valid C++17, should the fact that GCC doesn't even warn me (even though I enabled -Wall -Wextra -pedantic) be considered a bug?

推荐答案

C语正确.可以这么说,引用以常量表达式急切"地求值. [expr.const]/2.11:

Clang is correct. References are evaluated "eagerly" in constant expressions, so to speak. [expr.const]/2.11:

表达式e是核心常量表达式,除非求值 的e,按照抽象机的规则,将求出一个 以下表达式之一:

An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions:

  • [...]
  • 一个 id-expression ,它引用引用类型的变量或数据成员,除非引用具有前面的初始化,并且 任何一个
    • 使用常量表达式或
    • 进行初始化
    • 其寿命始于对e的评估;
    • [...]
    • an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization and either
      • it is initialized with a constant expression or
      • its lifetime began within the evaluation of e;

      这篇关于使用引用的constexpr静态成员作为模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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