【问题标题】:How can you perform arithmetic on an element of a non-type parameter pack?如何对非类型参数包的元素执行算术运算?
【发布时间】:2020-10-27 19:26:12
【问题描述】:

我想要一个返回带有修改过的参数包的对象的方法。例如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?
}

【问题讨论】:

  • 这听起来像XY problem 对我来说......你想达到什么目的?我不同意这个骗局。
  • @JHBonarius 如果您不同意关闭欺骗,请投票重新打开。
  • max66 有答案
  • @max66 您现在可以发布该答案:)
  • @cigien - 谢谢:我没有看到问题被重新打开:)

标签: c++ c++17 variadic-templates template-meta-programming


【解决方案1】:

如果你负担得起辅助方法,那么从 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, "!" );
 }

【讨论】:

  • 我冒昧地对您的代码进行了一些编辑...希望您不介意。注意std::is_same_v 是 C++17。
猜你喜欢
  • 2012-06-19
  • 2021-05-03
  • 2012-02-26
  • 2023-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
相关资源
最近更新 更多