如何在包扩展期间使用constexpr函数?
How can I use a constexpr function during pack expansion?
我想做以下事情:
// have a constexpr function
template<class T>
constexpr T square( T const i )
{
return i * i;
}
// transform a std::integer_sequence<> by calling the constexpr function on every integer
template<class Fn, class T, T... values>
static constexpr auto make_type( Fn fn, std::integer_sequence<T, values...> )
{
return std::integer_sequence<T, fn( values )...>{};
}
// so that I can use it like so
using type = decltype( make_type( square, std::integer_sequence<int, 1, 2, 3>{} ) );
但是,我得到以下错误:
…main.cpp|19|错误:'fn'不是常量表达式|
fn
在常量表达式中不可用——它是一个标准的块作用域变量。必须将函子作为类型传递。
template <typename Fn, typename T, T... values>
static constexpr std::integer_sequence<T, Fn{}(values)...>
make_type(std::integer_sequence<T, values...>) {return {};}
并将函数重写为
struct Square {
template <typename T> constexpr T operator()(T const& t)
{return t*t;}
};
除了constexpr
不是函数指针类型的一部分,square
是一个模板,所以你不能通过通常的隐式衰变形成指向它的指针。
但是,不需要更改make_type
函数的签名来使此工作。将Square
重写为函子:
struct Square {
template<class T>
constexpr T operator()( T const& i )
{
return i * i;
}
};
然后这样命名:
using type = decltype( make_type( square{}, std::integer_sequence<int, 1, 2, 3>{} ) );
在c++ 17中,您将能够使用constexpr
lambda:
constexpr auto square = [](auto const& i) { return i * i; };
using type = decltype( make_type( square, std::integer_sequence<int, 1, 2, 3>{} ) );
相关文章:
- 条件constexpr函数
- constexpr 函数中的非文字(通过 std::is_constant_evaluated)
- constexpr 函数获取常量字符*
- 如何在 constexpr 函数中实现回退运行时
- 在非 constexpr 函数中作为左值传递的变量上使用 'constexpr' 函数
- NVCC 错误:string_view.h:constexpr 函数返回是非常量
- constexpr函数中的静态constexpr变量
- 在 constexpr 函数中断言
- G++ 编译器是否在未使用返回值的情况下将 constexpr 函数视为常规函数?
- constexpr 函数的常量引用参数:gcc/msvc vs clang/icc
- constexpr 函数在编译时获取值,即使我的变量不是 constexpr
- 如何正确地对 constexpr 函数进行单元测试
- 为什么 std::launder 是一个 constexpr 函数?
- 我可以使用 constexpr 函数声明一个静态数组吗?
- 用于连接向量的 Constexpr 函数
- 在非constexpr函数上添加的constexpr限定符不会触发任何警告
- 为什么 std::get<T> 其中 T 是调用 constexpr 函数失败的结果?
- 在constexpr函数中插入许多模板
- 在enable_if_t中调用 constexpr 函数
- constexpr 函数中的 for 循环无法使用 MSVC 19.23 进行编译