问题描述
我有一个参数包充满默认可构造,然后可调用对象(如 ExampleFunctor
),并想要按顺序(从左到右)调用它们。如果返回类型是void以外的任何东西,我可以使用初始化器列表来做到这一点:
I have a parameter pack full of default constructable and then callable objects (like the ExampleFunctor
) and want to call all of them in order (left to right). If the return type is anything besides void I can use an initializer list to do this:
struct ExampleFunctor{
void operator()(){someGlobal = 4;}
};
template<typename... Ts>
struct CallThem {
void operator()(){
auto list = {Ts()()...};
}
}
但是如果返回类型是void this trick工作。
however if the return type is void this trick does not work.
我可以包装所有的ts在一个包装器返回一个int,但似乎overkill和这个代码将最终运行在32K闪存的cortex M3,所以额外的功能调试开销的包装是一个痛苦,如果我编译单元在调试模式(和调试在释放模式使我的大脑受伤)。
I could wrap all the Ts in a wrapper returning an int but that seems overkill and this code will be ultimately running on a cortex M3 with 32K of flash so the extra function call overhead of the wrapper is a pain if I compile the unit in debug mode (and debugging in release mode makes my brain hurt).
有更好的方法吗?
推荐答案
:
int someGlobal;
struct ExampleFunctor{
void operator()(){someGlobal = 4;}
};
template<typename... Ts>
struct CallThem {
void operator()(){
int list[] = {(Ts()(),0)...};
(void)list;
}
};
int main()
{
CallThem<ExampleFunctor, ExampleFunctor>{}();
}
Btw我没有使用 initializer_list
这里只是一个数组;尝试自己哪一个/如果他们中的任何一个可以被编译器丢弃。
(void)list
是禁止警告(未使用的变量)。
Btw I'm not using an initializer_list
here but just an array; try yourself which one / if any of them can be thrown away by the compiler. The (void)list
is to suppress a warning (unused variable).
这篇关于如果函数返回类型为void,那么如何调用可变参数包中的所有函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!