简体   繁体   English

非类型可变参数模板的运行时计算

[英]run-time calculations with non-type variadic templates

Is it possible to make run time calculations with non-type variadic templates? 是否可以使用非类型可变参数模板进行运行时计算?

Imagine the following situation: 想象一下以下情况:

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

The getPosition method should return the position of the given integer in the template parameter pack. getPosition方法应返回给定整数在模板参数包中的位置。 If the given integer is not present in the parameter pack, an error (preferably at compile time) should be generated. 如果参数包中不存在给定的整数,则应生成错误(最好在编译时)。

PS I know how to do this if the signature is changed to PS我知道如果签名更改为

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

Unfortunately, this is not an option for me as the method should be virtual. 不幸的是,这对我来说不是一个选择,因为该方法应该是虚拟的。

You could dump the indexes into a std::array and use std::find . 您可以将索引转储到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);
   }
};

You can't generate a compile-time error if target doesn't exist, as you only know target at run-time. 如果target不存在,则无法生成编译时错误,因为您仅在运行时知道target

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM