如何对非类型参数包的元素执行算术运算?

问题描述

我想要一个返回带有修改后的参数包的对象的方法。例如,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,"!" );
 }