静态 constexpr 函数在模板结构中工作,但不能在结构中工作.为什么?

static constexpr function work in template struct but not struct. Why?

本文关键字:工作 结构 但不能 为什么 constexpr 静态 函数      更新时间:2023-10-16

以下编译:

#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/binary/binary.hpp>
namespace x3 = boost::spirit::x3;
template <int dummy=0>
struct S {
static constexpr auto get_parse_rule() {
return x3::byte_ >> x3::byte_;
}
};
int main() {
auto parse_rule = S<>::get_parse_rule();
return 0;
}

但这不会:

#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/binary/binary.hpp>
namespace x3 = boost::spirit::x3;
struct S {
static constexpr auto get_parse_rule() {
return x3::byte_ >> x3::byte_;
}
};
int main() {
auto parse_rule = S::get_parse_rule();
return 0;
}

当我读这两篇文章时,我看到的是同样的东西,但显然它们不一样。有人可以启发我为什么会这样吗?

Constexpr 函数的返回类型必须是 LiteralType。提升精神返回不满足这些要求的东西。Constexpr 功能模板实例化可以在不满足要求时进行编译,但无论如何您都不会从中获得编译时常量。