我目前正在做一个项目,但遇到以下问题。
我有一个 C++ 方法,我想以两种不同的方式工作:
void MyFunction()
{
foo();
bar();
foobar();
}
void MyFunctionWithABonus()
{
foo();
bar();
doBonusStuff();
foobar();
}
而且我不想复制我的代码,因为实际的函数要长得多。 问题是我在任何情况下都不能在调用 MyFunction 而不是 MyFunctionWithABonus 时向程序添加执行时间。这就是为什么我不能只拥有一个通过 C++ 比较检查的 bool 参数。
我的想法是使用 C++ 模板来虚拟复制我的代码,但我想不出没有额外执行时间且不必复制代码的方法。
我不是模板专家,所以我可能会遗漏一些东西。
你们有什么想法吗?或者这在 C++11 中是不可能的?
最佳答案
这样的事情会做得很好:
template<bool bonus = false>
void MyFunction()
{
foo();
bar();
if (bonus) { doBonusStuff(); }
foobar();
}
通过以下方式调用它:
MyFunction<true>();
MyFunction<false>();
MyFunction(); // Call myFunction with the false template by default
可以通过向函数添加一些漂亮的包装器来避免“丑陋”的模板:
void MyFunctionAlone() { MyFunction<false>(); }
void MyFunctionBonus() { MyFunction<true>(); }
您可以找到有关该技术的一些不错的信息there .那是一篇“旧”论文,但技术本身完全正确。
如果您可以访问一个不错的 C++17 编译器,您甚至可以通过使用 constexpr if 进一步插入该技术,如下所示:
template <int bonus>
auto MyFunction() {
foo();
bar();
if constexpr (bonus == 0) { doBonusStuff1(); }
else if constexpr (bonus == 1) { doBonusStuff2(); }
else if constexpr (bonus == 2) { doBonusStuff3(); }
else if constexpr (bonus == 3) { doBonusStuff4(); }
// Guarantee that this function will not compile
// if a bonus different than 0,1,2,3 is passer
else { static_assert(false);},
foorbar();
}
关于c++ - 使用 c++11 复制代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43605206/