为什么引用上的constexpr函数不是constexpr? [英] Why is a constexpr function on a reference not constexpr?

查看:130
本文介绍了为什么引用上的constexpr函数不是constexpr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下功能:

template <size_t S1, size_t S2>
auto concatenate(std::array<uint8_t, S1> &data1, std::array<uint8_t, S2> &data2) {
    std::array<uint8_t, data1.size() + data2.size()> result;

    auto iter = std::copy(data1.begin(), data1.end(), result.begin());
    std::copy(data2.begin(), data2.end(), iter);

    return result;
}

int main()
{
    std::array<uint8_t, 1> data1{ 0x00 };
    std::array<uint8_t, 1> data2{ 0xFF };

    auto result = concatenate(data1, data2);
    return 0;
}

在使用clang 6.0以及-std = c ++ 17进行编译时,此函数无法编译,因为数组上的size成员函数由于是引用而不是constexpr.错误消息是这样的:

When compiled using clang 6.0, using -std=c++17, this function does not compile, because the size member function on the array is not constexpr due to it being a reference. The error message is this:

错误:非类型模板参数不是常量表达式

error: non-type template argument is not a constant expression

当参数不是 引用时,代码将按预期工作.

When the parameters are not references, the code works as expected.

我想知道为什么会这样,因为size()实际上返回模板参数,所以几乎不可能再是const了.该参数是否为引用都无济于事.

I wonder why this would be, as the size() actually returns a template parameter, it could hardly be any more const. Whether the parameter is or is not a reference shouldn't make a difference.

我知道我当然可以使用S1和S2模板参数,该功能只是问题的简短说明.

I know I could of course use the S1 and S2 template parameters, the function is merely a short illustration of the problem.

标准中是否有任何内容?令我感到惊讶的是编译错误.

Is there anything in the standard? I was very surprised to get a compile error out of this.

推荐答案

因为您已经评估了参考文献.来自 [expr.const]/4 :

Because you have evaluated a reference. From [expr.const]/4:

表达式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 usable in constant expressions or
      • its lifetime began within the evaluation of e;

      您的参考参数没有事先进行初始化,因此无法在常量表达式中使用.

      Your reference parameter has no preceding initialization, so it cannot be used in a constant expression.

      您可以在这里直接使用S1 + S2.

      You can simply use S1 + S2 instead here.

      这篇关于为什么引用上的constexpr函数不是constexpr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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