我有这个计算两个索引序列的元素乘积的实现
template<size_t...Is,size_t...Js>
constexpr auto product_sequence_impl( index_sequence<Is...>,
index_sequence<Js...> ) ->
decltype( index_sequence<(Is*Js)...>() );
template<typename S1, typename S2> using product_sequence =
decltype( product_sequence_impl( declval<S1>(), declval<S2>() ) );
这按预期工作,因此当我运行以下代码时
using A = index_sequence<0,1,2>;
using B = index_sequence<3,4,5>;
using C = product_sequence<A,B>;
print_sequence( A{}, cout );
print_sequence( B{}, cout );
print_sequence( C{}, cout );
我看到得到了想要的输出
[ 0 1 2 ]
[ 3 4 5 ]
[ 0 4 10 ]
接下来我尝试创建一个元函数,它可以应用两个序列的成对结果类:
template<template<size_t,size_t> class binary_mfun>
struct binseq_mfun_impl {
template<size_t...Is, size_t...Js>
constexpr auto method( index_sequence<Is...>,
index_sequence<Js...> ) ->
decltype( index_sequence<binary_mfun<Is,Js>::value...>() );
template<typename S1, typename S2>
using type = decltype( declval<S1>(), declval<S2>() );
};
template<template<size_t,size_t> class binary_mfun, typename S1, typename S2>
using binseq_mfun = typename binseq_mfun_impl<binary_mfun>::template type<S1,S2>;
成对乘积的实现在哪里
template<size_t I, size_t J>
struct binary_product {
static constexpr size_t value = I*J;
};
但是,当我运行这段代码时
using D = binseq_mfun<binary_product,A,B>;
print_sequence( D{}, cout );
我知道 D
与 B
具有相同的值。看起来 binary_mfun
永远不会被使用。我也尝试使用函数来实现这个
方法,但是我不清楚如何处理模板模板
参数
template<template<size_t,size_t> typename binary_mfun, size_t...Is, size_t...Js>
constexpr auto binseq_mfun_impl( binary_mfun /*<?,?>*/,
index_sequence<Is...>,
index_sequence<Js...> ) ->
index_sequence<binary_mfun<Is,Js>::value...>;
template<typename binary_mfun, typename S1, typename S2>
using binseq_mfun =
decltype(binseq_mfun_impl( declval<binary_mfun>(),
declval<S1>(),
declval<S2>() ) );
最佳答案
感谢 Quentin 和 Barry 的评论以及意识到 method
需要是 static
这里是一个完整的工作版本:
// Metafunction for binary operations on sequences
template<template<size_t,size_t> class binary_mfun>
struct binseq_mfun_impl {
template<size_t...Is, size_t...Js>
static constexpr auto method( index_sequence<Is...>,
index_sequence<Js...> ) ->
index_sequence<binary_mfun<Is,Js>::value...>;
template<typename S1, typename S2>
using type = decltype( method( declval<S1>(), declval<S2>() ) );
};
template<template<size_t,size_t> class binary_mfun, typename S1, typename S2>
using binseq_mfun = typename binseq_mfun_impl<binary_mfun>::template type<S1,S2>;
// Example binary function
template<size_t I, size_t J>
struct binary_product { static constexpr size_t value = I*J; };
// Example usage
using A = index_sequence<0,1,2>;
using B = index_sequence<3,4,5>;
using C = binseq_mfun<binary_product,A,B>; // Has values 0,4,10
关于c++ - 如何实现对序列对进行操作的 C++ 元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52504311/