小编Bea*_*ean的帖子

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

在这里,我想将我的 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 …
Run Code Online (Sandbox Code Playgroud)

c++ pointers reference

3
推荐指数
1
解决办法
80
查看次数

标签 统计

c++ ×1

pointers ×1

reference ×1