gpt4 book ai didi

c++ - 迭代模板参数列表?

转载 作者:太空狗 更新时间:2023-10-29 19:49:14 25 4
gpt4 key购买 nike

我正在尝试寻找一种循环遍历模板参数列表但没有成功的方法

我不能使用 c++11 可变参数模板功能,它需要在编译时完成

我可以假设在否定论据之后不会有肯定论据

有什么想法吗?

template< int F1, int F2 ,int F3>
struct TemplatedClass
{
TemplatedClass();
update()
{
/*
for each positive template argument
call a method
*/
}
};

最佳答案

除了编写一系列 if 语句之外,您还可以将所有参数放入一个数组中并遍历它。这样编译器将无法优化您的代码(您没有指定是否需要这样做),但我认为它看起来会更干净。例如

template<int F1, int F2 ,int F3>
struct TemplatedClass
{
TemplatedClass();
update()
{
const int array[] = {F1, F2, F3};
// replace this with std::for_each(...) with functors you need
for (int i = 0; i < sizeof(array)/sizeof(array[0]); ++i)
{
myfunc(array[i]);
}
}
}

关于c++ - 迭代模板参数列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11562223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com