相关疑难解决方法(0)

constexpr是一个std :: array的开头

我无法理解为什么gcc-8.2.0和clang-7.0.0都拒绝以下代码(这里的实时代码):

#include <array>

int main() {

    constexpr std::array<int,3> v{1,2,3};
    constexpr auto b = v.begin(); // error: not a constexpr 
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

有错误

error: '(std::array<int, 3>::const_pointer)(& v.std::array<int,3>::_M_elems)' 
is not a constant expression (constexpr auto b = v.begin();)
Run Code Online (Sandbox Code Playgroud)

根据en.cppreference.com,begin()声明了成员函数constexpr.这是编译器错误吗?

c++ constexpr c++17

28
推荐指数
1
解决办法
986
查看次数

为什么这个表达式不是一个常量表达式?

b此代码中的表达式应为核心常量表达式

int main()
{
    constexpr int a = 10;
    const int &b = a;
    constexpr int c = b; // here
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

由于标准说(8.20,第2段[expr.const]在N4700)

表达式e核心常量表达式,除非评估 e将评估以下表达式之一:

  • ...

  • 除非适用,否则左值 - 右值转换(7.1)

    • ...

    • 非易失性glvalue,引用constexpr定义的非易失性对象,或引用此类对象的不可变子对象,或者

首先,b上面代码中的表达式是一个左值(也是一个glvalue),因为它是一个引用,因此是一个变量(8.1.4.1,第1段[expr.prim.id.unqual]):

如果实体是函数,变量或数据成员,则表达式是左值 ,否则为prvalue; 如果标识符指定位字段(11.5),则它是位字段.

其次,变量b表示的对象是a,并且声明了它constexpr.但是,gcc抱怨道

./hello.cpp: In function ‘int main()’:
./hello.cpp:6:20: error: the value of ‘b’ is not usable in a constant expression
  constexpr int …
Run Code Online (Sandbox Code Playgroud)

c++ language-lawyer c++17

13
推荐指数
1
解决办法
1211
查看次数

使用const引用的Constexpr类未编译

我有以下示例代码

template<class T1, class T2>
class Operation
{
public:
    constexpr Operation(const T1& lhs, const T2& rhs) noexcept
        : m_lhs(lhs), m_rhs(rhs) { }

private:
    const T1& m_lhs;
    const T2& m_rhs;
};

int main()
{
    constexpr int a = 3;
    constexpr int b = 4;

    constexpr Operation op(a, b);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我用cygwin(gcc 8.2)编译

template<class T1, class T2>
class Operation
{
public:
    constexpr Operation(const T1& lhs, const T2& rhs) noexcept
        : m_lhs(lhs), m_rhs(rhs) { }

private:
    const T1& m_lhs;
    const T2& m_rhs; …
Run Code Online (Sandbox Code Playgroud)

c++ reference constexpr c++17

2
推荐指数
1
解决办法
81
查看次数

标签 统计

c++ ×3

c++17 ×3

constexpr ×2

language-lawyer ×1

reference ×1