你知道C++如何在一个函数内返回不同类型吗?

C++ 中要在一个函数内返回不同类型的值,你可以使用 C++17 引入的 std::variant 或 std::any,或者使用模板和多态。下面将分别介绍这些方法。

方法一:使用 std::variant

std::variant 允许你在一个函数内返回不同类型的值,但它要求所有可能的返回类型都在一个有限的集合中,你需要提前定义这个集合。

首先,包括 <variant> 头文件:

#include <variant>

然后,使用 std::variant 来定义函数的返回类型:

std::variant<int, double, std::string> GetDifferentValue(int choice) {     if (choice == 0) {         return 42;     } else if (choice == 1) {         return 3.14;     } else {         return "Hello, World!";     } }

在这个示例中,GetDifferentValue 函数可以返回 int、double 或 std::string,具体返回哪种类型取决于 choice 参数的值。

方法二:使用 std::any

std::any 允许你在一个函数内返回不同类型的值,而无需提前定义可能的返回类型。但在使用 std::any 时,你需要小心类型安全和类型转换。

首先,包括 <any> 头文件:

#include <any>

然后,使用 std::any 来定义函数的返回类型:

std::any GetDifferentValue(int choice) {     if (choice == 0) {         return 42;     } else if (choice == 1) {         return 3.14;     } else {         return "Hello, World!";     } }

在这个示例中,GetDifferentValue 函数可以返回任何类型的值。

方法三:使用模板和多态

另一种方式是使用模板和多态,这样你可以在运行时动态确定返回的类型。这通常需要创建一个基类,派生出具体类型的子类,并使用基类指针或智能指针进行返回。

#include <iostream> #include <memory>  class Base { public:     virtual void print() const = 0; };  class IntType : public Base { public:     IntType(int value) : value(value) {}     void print() const override {         std::cout << "Int: " << value << std::endl;     }  private:     int value; };  class DoubleType : public Base { public:     DoubleType(double value) : value(value) {}     void print() const override {         std::cout << "Double: " << value << std::endl;     }  private:     double value; };  class StringType : public Base { public:     StringType(const std::string& value) : value(value) {}     void print() const override {         std::cout << "String: " << value << std::endl;     }  private:     std::string value; };  std::unique_ptr<Base> GetDifferentValue(int choice) {     if (choice == 0) {         return std::make_unique<IntType>(42);     } else if (choice == 1) {         return std::make_unique<DoubleType>(3.14);     } else {         return std::make_unique<StringType>("Hello, World!");     } }  int main() {     auto value = GetDifferentValue(2);     value->print();     return 0; }

在这个示例中,GetDifferentValue 返回一个指向 Base 基类的智能指针,而 Base 有多个派生类,代表不同的返回类型。

以上是三种在 C++ 中返回不同类型的方法,你可以根据具体需求选择其中之一。

你知道C++如何在一个函数内返回不同类型吗?

发表评论

评论已关闭。

相关文章