在c++中动态引用不同类型的变量?

Bea*_*ean 3 c++ pointers reference

在这里,我想将我的 C++ 代码从版本 2 简化为版本 1。在像 Python 这样的语言中,引用不同类型的变量(如版本 1)很简单。如何在 C++ 中实现类似的代码?

\n
#include <iostream>\n#include <vector>\n\n/* version 1: compile failed */\nvoid display(std::vector<int> vi, std::vector<double> vd) {\n  // error: operands to ?: have different types\n  // \xe2\x80\x98std::vector<double>\xe2\x80\x99 and \xe2\x80\x98std::vector<int>\xe2\x80\x99\n  auto& v = vi.empty() ? vd : vi;\n  for (const auto &e : v) {\n    std::cout << e << " ";\n  }\n}\n\n/* version 2 */\nvoid display(std::vector<int> vi, std::vector<double> vd) {\n  if (!vi.empty()) {\n    for (const auto &e : vi) {\n      std::cout << e << " ";\n    }\n  } else {\n    for (const auto &e : vd) {\n      std::cout << e << " ";\n    }\n  }\n}\n\n\n\nint main(int argc, char *argv[]) {\n  std::vector<int> vi{0, 1, 2};\n  std::vector<double> vd{10., 11, 12};\n\n  // one of vi, vd can be empty after some modifications\n  ...\n\n  display(vi, vd);\n  return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

补充:

\n

这里的打印功能只是一个例子。我的主要目的是创建一个引用std::vector<int>std::vector<double>根据它们是否为空。下面的例子可以

\n
#include <iostream>\n#include <vector>\n\nvoid process_1(std::vector<int> v) {\n  for (const auto &e : v) {\n    std::cout << e << " ";\n  }\n  std::cout << std::endl;\n}\n\nvoid process_1(std::vector<double> v) {\n  double sum = 0;\n  for (const auto &e : v) {\n    sum += e;\n  }\n  std::cout << sum << std::endl;\n}\n\nvoid process_2(std::vector<int>) {\n  //...\n}\n\nvoid process_2(std::vector<double>) {\n  //...\n}\n\n/* Version 2 */\nint version_2(int argc, char *argv[]) {\n  std::vector<int> vi{0, 1, 2};\n  std::vector<double> vd{10., 11, 12};\n\n  if (!vi.empty()) {\n    process_1(vi);\n  } else {\n    process_1(vd);\n  }\n\n  // do something\n\n  if (!vi.empty()) {\n    process_2(vi);\n  } else {\n    process_2(vd);\n  }\n\n  return 0;\n}\n\n/* Version 1 */\nint version_1(int argc, char *argv[]) {\n  std::vector<int> vi{0, 1, 2};\n  std::vector<double> vd{10., 11, 12};\n\n  // in Python, it\'s easy to create a reference dynamically, eg:\n  // ref = vd is len(vi) == 0 else vi\n  auto &ref = vd if vi.empty() else vi;\n\n  process_1(ref);\n  // do something\n  process_2(ref);\n\n  return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

Igo*_*nik 5

也许是这样的:

void display(const std::vector<int>& vi, const std::vector<double>& vd) {
  auto print_sequence = [](const auto& v) {
    for (const auto &e : v) {
      std::cout << e << " ";
    }
  }
  vi.empty() ? print_sequence(vd) : print_sequence(vi);
}
Run Code Online (Sandbox Code Playgroud)