运行-使用非类型可变参数模板的时间计算

run-time calculations with non-type variadic templates

是否可以使用非类型可变参数模板进行 运行 时间计算?

想象一下以下情况:

template<unsigned int... indexes>
struct s
{
   unsigned int getPosition(const unsigned int target) const;
};

s<2,5,0,7> obj;
std::cout << obj.getPosition(5) << std::endl; //< this should output 1
std::cout << obj.getPosition(2) << std::endl; //< this should output 0

getPosition方法应该return给定整数在模板参数包中的位置。如果参数包中不存在给定的整数,则应生成错误(最好是在编译时)。

P.S。如果将签名更改为

我知道如何执行此操作
template<unsigned int... indexes>
struct s
{
   template<unsigned int target>
   unsigned int getPosition() const;
};

不幸的是,这不是我的选择,因为该方法应该是虚拟的。

您可以将索引转储到 std::array 并使用 std::find

struct s
{
   unsigned int getPosition(const unsigned int target) const {
       static std::array<int, sizeof...(indexes)> indexArray { indexes... };
       auto pos = std::find(std::begin(indexArray), std::end(indexArray), target);

       if (pos == std::end(indexArray)) {
           //handle error, probably an exception   
       }

       return std::distance(std::begin(indexArray), pos);
   }
};

如果 target 不存在,您不能生成 compile-time 错误,因为您只知道 target 在 run-time。