如何检测是否有一个函数.是一个constexpr?并标记其他功能.constexpr取决于它?

Ama*_*rab 19 c++ constexpr c++11 c++14

假设我有一些功能模板f1:

template<typename f2>
int f1(int i, int j) noexcept {
  return i + j + f2(i, j);
}
Run Code Online (Sandbox Code Playgroud)

有没有办法确定是否f2(i, j)可以constexpr.(无论它是函数还是函子),所以也标记f1<f2>constexpr

我想在这里使用SFINAE一些如何,但没有找到如何检测constexpr使用类型特征

Jar*_*d42 11

你可以标记f1constexpr.

template<typename f2>
constexpr int f1(int i, int j) noexcept {
  return i + j + f2(i, j);
}
Run Code Online (Sandbox Code Playgroud)

模板函数f1将是constexpriif f2.

如果f2不是,只有f1在常量编译时表达式中使用时才会出现错误.

演示


101*_*010 7

检查函数(例如foo)是否的最简单方法constexpr是将其返回值分配给constexpr如下:

  constexpr auto i = foo();
Run Code Online (Sandbox Code Playgroud)

如果返回的值不是constexpr编译将失败.

如果您想要SFINAE测试来检查函数(例如foo)constexpr是否可以使用std::integral_constant类型特征:

std::integral_constant<int, foo()>::value
Run Code Online (Sandbox Code Playgroud)

现场演示

  • 这似乎没有任何SFINAE友好 (4认同)