use*_*177 5 c++ template-meta-programming
我想做以下事情:
// 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>{} ) );
Run Code Online (Sandbox Code Playgroud)
但是,我收到以下错误:
...\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 {};}
Run Code Online (Sandbox Code Playgroud)
并将您的功能重写为
struct Square {
template <typename T> constexpr T operator()(T const& t)
{return t*t;}
};
Run Code Online (Sandbox Code Playgroud)