[英]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
方法应返回给定整数在模板参数包中的位置。 如果参数包中不存在给定的整数,则应生成错误(最好在编译时)。
PS我知道如果签名更改为
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
不存在,则无法生成编译时错误,因为您仅在运行时知道target
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.