c++ - 使用 c++11 复制代码

标签 c++ c++11 templates

我目前正在做一个项目,但遇到以下问题。

我有一个 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/

相关文章:

c++ - sort() 是否自动使用 move 语义?

c++ - 为 STL 算法 lambda 适配 std::pair

C++ Utility将长switch语句转换为封装switch case阶梯的简洁函数调用

c++ - 强制编译器生成整个类模板

c++ - 即使所有文件都使用 fPIC 编译,ld 也无法将静态库链接到动态库

c++ - 在代码块中运行发布版本时出现段错误,但运行调试版本时不会出现段错误

c++ - 在类构造函数中初始化结构的正确方法

c++ - 模板和函数指针 : How do I define a function-pointer that was declared in a template class?

c++ - 这个链表遍历有什么问题?

c++ - 数据类型与模板参数不同的模板对象