Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用非类型可变模板的运行时计算_C++_Variadic Templates - Fatal编程技术网

C++ 使用非类型可变模板的运行时计算

C++ 使用非类型可变模板的运行时计算,c++,variadic-templates,C++,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 ou

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

想象一下以下情况:

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

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

您可以将索引转储到
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);
   }
};
结构
{
无符号整数getPosition(常量无符号整数目标)常量{
静态std::数组索引数组{index…};
自动pos=std::find(std::begin(indexArray)、std::end(indexArray)、target);
if(pos==std::end(indexArray)){
//处理错误,可能是异常
}
返回标准::距离(标准::开始(索引排列),位置);
}
};

如果
target
不存在,则无法生成编译时错误,因为您只能在运行时知道
target

您可以将索引转储到
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);
   }
};
结构
{
无符号整数getPosition(常量无符号整数目标)常量{
静态std::数组索引数组{index…};
自动pos=std::find(std::begin(indexArray)、std::end(indexArray)、target);
if(pos==std::end(indexArray)){
//处理错误,可能是异常
}
返回标准::距离(标准::开始(索引排列),位置);
}
};

如果
target
不存在,则无法生成编译时错误,因为您只知道在运行时
target

谢谢,这非常有用。您是否知道如何修改解决方案(或函数签名/设计),以便在编译时完成计算。我知道这个函数只能用编译时常量调用。但是我还没有找到一种方法来向编译器表达它(除了使用模板函数)?我认为您也需要将
静态
从数组中移除。似乎
std::find
不是
constexpr
函数。您可以在循环中进行搜索。谢谢,这非常有帮助。您是否知道如何修改解决方案(或函数签名/设计),以便在编译时完成计算。我知道这个函数只能用编译时常量调用。但是我还没有找到一种方法来向编译器表达它(除了使用模板函数)?我认为您也需要将
静态
从数组中移除。似乎
std::find
不是
constepr
函数。您可以在循环中进行搜索。