gpt4 book ai didi

c++ - C++14封装大量参数

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:23:19 25 4
gpt4 key购买 nike

我想编写一个使用很多参数的函数,我将其称为abc。我有四种在 C++14 中实现它的选择。

对于 2018 年新的现代 C++ 项目,这些风格中的哪一种最符合 ISO C++ 的理念? ?其他风格指南推荐哪些风格?

面向对象风格

class Computer {
int a, b, c;
public:
Computer(int a, int b, int c) : a(a), b(b), c(c) {}
int compute(int) const {
// do something with a, b, c
}
};
...
const Computer computer(a, b, c);
int result = computer.compute(123);

优点:

  • C++程序员容易掌握

缺点:

  • 要在 map 或 fold 操作中计算事物,我们必须执行笨拙的 [computer](int input){ return computer.compute(input); }

C 风格

struct ComputeParams {
int a, b, c;
};

int compute(const ComputeParams &params, int input) {
// do something with params.a, params.b, params.c
}
...
const ComputeParams params{a, b, c};
int result = compute(params, 123);

优点:

  • C 程序员容易掌握

缺点:

  • compute 的详细实现涉及调用 params.a 而不是 a
  • 冗长的调用,每次都必须传入一个结构。

仿函数风格

struct Computor {
int a, b, c;
int operator()(int input) const {
// do something with a, b, c
}
};
...
const Computor compute{a, b, c};
int result = compute(123);

优点:

  • 面向对象风格的所有优点,加上它看起来像一个函数
  • 可用于函数式操作,例如 map、fold 和 for_each

缺点:

  • “仿函数”这个词看起来很时髦。

函数式风格

auto genCompute(int a, int b, int c) {
return [a, b, c](int input) -> int {
// do something with a, b, c
}
}
...
auto compute = genCompute(a, b, c);
int result = compute(123);

优点:

  • OCaml 程序员易于掌握
  • 可用于函数式操作,例如 map、fold 和 for_each
  • 技术上与仿函数相同

缺点:

  • C++ 和 C 程序员很难掌握
  • 由于 lambda 函数是由编译器生成的独特类型,可能需要使用 auto 或模板魔术来内联 lambda 函数,或使用 std::function性能开销
  • 无法接受虚表和多态继承的力量

最佳答案

函数式风格还有很多话要说:您可以轻松地为某些参数值提供特殊/优化的版本

std::function<int(int)> getCompute(int a, int b, int c)
{
if(a==0)
return [b,c](int input) { /* version for a=0 */ };
if(b==0)
return [a,c](int input) { /* version for b=0 */ };
if(c==0)
return [a,b](int input) { /* version for c=0 */ };
/* more optimized versions */
return [a,b,c](int input) { /* general version */ };
}

其他选项的等效项并不简单。不幸的是,这需要使用 std::function 来包装不同的 lambda。

关于c++ - C++14封装大量参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48999883/

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