如何对非类型参数包的元素执行算术运算?
How can you perform arithmetic on an element of a non-type parameter pack?
我想要一种方法,该方法 returns 具有修改参数包的对象。比如Nth
模板参数加1。
template<size_t... Ni>
struct Test
{
template<size_t Nth>
constexpr auto RunTest()
{
// What should be written here?
}
};
int main()
{
Test<2, 2, 2> t1;
Test<2, 3, 2> t2 = t1.RunTest<1>(); // How to make this work?
}
如果您负担得起辅助方法,那么从 C++14 开始,以下方法应该可行:
#include <utility>
#include <type_traits>
template <std::size_t... Ni>
struct PackHolder
{
template <std::size_t Nth, std::size_t ... Is>
constexpr auto IncrementHelper (std::index_sequence<Is...>)
-> PackHolder<(Ni + (Nth == Is))...>
{ return {}; }
template <std::size_t Nth>
constexpr auto IncrementPackElement()
{ return IncrementHelper<Nth>(std::make_index_sequence<sizeof...(Ni)>{}); }
};
int main()
{
PackHolder<2, 2, 2> t1;
auto t2 = t1.IncrementPackElement<1>();
static_assert( std::is_same<decltype(t2), PackHolder<2, 3, 2>>::value, "!" );
}
我想要一种方法,该方法 returns 具有修改参数包的对象。比如Nth
模板参数加1。
template<size_t... Ni>
struct Test
{
template<size_t Nth>
constexpr auto RunTest()
{
// What should be written here?
}
};
int main()
{
Test<2, 2, 2> t1;
Test<2, 3, 2> t2 = t1.RunTest<1>(); // How to make this work?
}
如果您负担得起辅助方法,那么从 C++14 开始,以下方法应该可行:
#include <utility>
#include <type_traits>
template <std::size_t... Ni>
struct PackHolder
{
template <std::size_t Nth, std::size_t ... Is>
constexpr auto IncrementHelper (std::index_sequence<Is...>)
-> PackHolder<(Ni + (Nth == Is))...>
{ return {}; }
template <std::size_t Nth>
constexpr auto IncrementPackElement()
{ return IncrementHelper<Nth>(std::make_index_sequence<sizeof...(Ni)>{}); }
};
int main()
{
PackHolder<2, 2, 2> t1;
auto t2 = t1.IncrementPackElement<1>();
static_assert( std::is_same<decltype(t2), PackHolder<2, 3, 2>>::value, "!" );
}