简体   繁体   English

即使成员函数是constexpr,为什么还需要constexpr?

[英]Why is constexpr required even though member function is constexpr?

The following does not compile unless I put constexpr before initializer_list: 除非我在initializer_list之前放置constexpr,否则以下内容无法编译:

constexpr std::initializer_list<int> il = {
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
std::array<int, il.size()> a;

But initializer_list size is constexpr: 但是initializer_list的大小是constexpr:

constexpr size_type size() const;
std::initializer_list<int> il = rand() ? std::initializer_list<int>{1}
                                       : std::initializer_list<int>{1,2,3};

std::array<int, il.size()> a;

That's why. 这就是为什么。

A constexpr member function is a function that can be executed within a constant expression, it doesn't necessarily yield a result that is a compile-time constant. constexpr成员函数是一个可以在常量表达式中执行的函数,它不一定产生一个编译时常量的结果。 For example: 例如:

struct S
{
    int m;
    constexpr int foo() const { return m; }
};

S s{rand()};
int j = s.foo();     // only known at run-time

constexpr S cs{42};
int arr[cs.foo()];   // compile-time constant

By writing std::array<int, il.size()> a; 通过编写std::array<int, il.size()> a; you are claiming that il.size() can be evaluated at compile time with a constant result, allowing template instantiation. 你声称可以在编译时使用常量结果评估il.size() ,允许模板实例化。

That's why both the initializer_list::size() method and your il variable need to be declared as constexpr . 这就是为什么initializer_list::size()方法和你的il变量都需要声明为constexpr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在调用此constexpr静态成员函数时不将其视为constexpr? - Why is this constexpr static member function not seen as constexpr when called? 为什么引用上的 constexpr 函数不是 constexpr? - Why is a constexpr function on a reference not constexpr? Consexpr 成员 function - Constexpr member function 有条件的 constexpr 成员函数 - Conditionally constexpr member function 通过调用constexpr函数定义静态constexpr成员 - Defining a static constexpr member by call to constexpr function 非constexpr可构造类的constexpr成员函数 - constexpr member function of non constexpr constructible class 为什么编译器会抱怨对constexpr函数的未定义引用,即使它是在另一个源文件中定义的? - Why does the compiler complain about undefined reference to a constexpr function even though it is defined in another source file? 即使我的变量不是 constexpr,constexpr 函数也会在编译时获取值 - constexpr function gets value at compile time even though my variable is not constexpr 非 constexpr 变量成员调用在具有条件的 constexpr 类成员函数中编译 - 为什么? - Non-constexpr variant member call compiling inside constexpr class member function with condition - why? 是否在constexpr静态成员的声明中需要constexpr说明符在类外部初始化? - Is the constexpr specifier required on the declaration of a constexpr static member initialized outside of the class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM