你知道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++ 中返回不同类型的方法,你可以根据具体需求选择其中之一。

责任编辑:姜华 来源: 今日头条
相关推荐

2011-04-11 13:08:13

对象链表C++

2020-11-17 08:07:29

存储类型浏览器

2016-11-14 16:37:44

2011-03-30 08:27:48

C#

2022-04-13 09:30:00

C++二分图图着色

2015-04-29 10:02:45

框架如何写框架框架步骤

2024-01-29 01:30:00

函数C++编程

2013-06-26 13:59:38

2022-09-21 09:03:46

机密计算数据安全

2022-05-09 10:47:08

登录SpringSecurity

2020-10-16 15:06:59

开发技术方案

2021-05-28 18:12:51

C++设计

2024-01-17 23:10:59

C++函数模板开发

2023-03-24 16:21:08

2023-11-23 13:39:17

2017-03-06 15:36:39

敏捷开发反馈信息

2022-03-24 14:49:57

HTTP前端

2024-02-19 08:11:40

C++编程尾返回类型推导

2022-01-05 11:40:36

Go特性语言

2020-04-08 08:35:20

JavaScript模块函数
点赞
收藏

51CTO技术栈公众号