我目前正在做一个项目,我有以下问题。
我有一个C++方法,我想以两种不同的方式工作:
void MyFunction()
{
foo();
bar();
foobar();
}
void MyFunctionWithABonus()
{
foo();
bar();
doBonusStuff();
foobar();
}我不想重复我的代码,因为实际的函数要长得多。问题是,在任何情况下,当调用MyFunction而不是MyFunctionWithABonus时,我都不能给程序增加执行时间。这就是为什么我不能只有一个布尔参数,我用C++比较来检查它。
我的想法是使用C++模板来虚拟地复制我的代码,但我想不出一种方法,在这种方法中,我没有额外的执行时间,也不需要复制代码。
我不是一个模板专家,所以我可能会遗漏一些东西。
你们中有谁有主意吗?或者这在C++11中是不可能的?
发布于 2017-04-25 16:25:44
使用模板和lambda,您可以这样做:
template <typename F>
void common(F f)
{
foo();
bar();
f();
foobar();
}
void MyFunction()
{
common([](){});
}
void MyFunctionWithABonus()
{
common(&doBonusStuff);
}或者,您可以只创建prefix和suffix函数。
void prefix()
{
foo();
bar();
}
void suffix()
{
foobar();
}
void MyFunction()
{
prefix();
suffix();
}
void MyFunctionWithABonus()
{
prefix();
doBonusStuff();
suffix();
}发布于 2017-04-25 19:11:10
考虑到OP对调试所做的一些评论,这里有一个版本,它为调试构建调用doBonusStuff(),但不调用发布构建(定义NDEBUG):
#if defined(NDEBUG)
#define DEBUG(x)
#else
#define DEBUG(x) x
#endif
void MyFunctionWithABonus()
{
foo();
bar();
DEBUG(doBonusStuff());
foobar();
}如果您希望检查某个条件,也可以使用assert macro,如果条件为假,则会失败(但仅适用于调试版本;发布版本不会执行检查)。
如果doBonusStuff()有副作用,要小心,因为这些副作用不会出现在发布版本中,并且可能会使代码中的假设无效。
发布于 2017-04-25 18:24:56
以下是使用可变模板的Jarod42答案的一个细微变化,因此调用者可以提供零个或一个奖励函数:
void callBonus() {}
template<typename F>
void callBonus(F&& f) { f(); }
template <typename ...F>
void MyFunction(F&&... f)
{
foo();
bar();
callBonus(std::forward<F>(f)...);
foobar();
}调用代码:
MyFunction();
MyFunction(&doBonusStuff);https://stackoverflow.com/questions/43605206
复制相似问题