首页 > 解决方案 > static constexpr 函数在模板结构中工作,但不在结构中。为什么?

问题描述

以下编译:

#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;
}

当我阅读这两篇文章时,我看到了相同的东西,但显然它们并不相同。有人可以告诉我为什么会这样吗?

标签: c++staticconstexpr

解决方案


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


推荐阅读