首页 > 编程语言 >你知道C++如何在一个函数内返回不同类型吗?

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

时间:2023-12-01 09:02:52浏览次数:36  
标签:返回 std return 函数 C++ choice GetDifferentValue 类型

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

标签:返回,std,return,函数,C++,choice,GetDifferentValue,类型
From: https://www.cnblogs.com/hanbing81868164/p/17868824.html

相关文章

  • 【复变函数】[杂记]唉,三元数
    前言  本文记录了一场对于“三元数”的无疾而终的探索。  起初,我只是想把复平面推广至三维。在读罢钟玉泉《复变函数论》的第一章第3节关于辐角和模的部分后,这个想法很自然而然地出现了。  随后,我发现这个东西其实早就有名字了,也就是”三元数“。问题引入  由离散数......
  • 实验四 现代C++标准库类与模板
    实验任务1task1.cpp源码task1_1.cpp:#include<iostream>usingstd::cout;usingstd::endl;//类A的定义classA{public:A(intx0,inty0):x{x0},y{y0}{}voidshow()const{cout<<x<<","<<y<<endl;}......
  • 实验4 现代C++标准库与类模板
    实验任务5textcoder.hpp#programonce#include<iostream>#include<string>usingnamespacestd;classTextCoder{private:stringtext;voidencoder();voiddecoder();public:TextCoder(string&str);stringget_ciphertext(......
  • 实验4 现代C++标准库与类模板
    实验任务51#include<iostream>2#include<string>3usingnamespacestd;4classTextCoder5{6public:7TextCoder()=default;8TextCoder(stringstr);9stringget_ciphertext();10stringget_deciphertext();11......
  • Linux Mint(Ubuntu)系统VS Code C/C++环境配置include error问题
    1.问题描述安装完成LinuxMint后发现随系统自带了gcc,心里比较开心,以为自己不需要装了。但是在安装完VSCode之后,一直提示#includeerrorsdetected.PleaseupdateyourincludePath.Squigglesaredisabledforthistranslationunitlinux2.解决方案重新通过apt安装gcc......
  • 实验4 现代c++标准库与类模板
    实验任务1task1.cpp源码task1_1.cpp:1#include<iostream>23usingstd::cout;4usingstd::endl;56//类A的定义7classA{8public:9A(intx0,inty0):x{x0},y{y0}{}10voidshow()const{cout<<x<<","<......
  • 列表操作符与函数 airScript 1
    #组合操作符并不改变原来的列表的值a=[1,1,1,2]b=[2,2,2,3]c=a+b#print(c)#重复运算符*#print(b*3)##成员资格操作符in#print(2inb)#函数a=[1,2,3,1,1,1]#a.append("haha")#print(a)#b=[3,4,5]a=[1,2,3,1,1,1]#a.extend(b)#改变了a的值,#print......
  • 实验四 现代c++ 标准库与类的模板
    1.普通数组、array、vector的相关性,以及,区别相关性存储多个元素:1.普通数组:使用C风格数组声明和定义,大小固定。2.array:是C++11引入的标准库容器,提供了数组的替代,大小固定。3.vector:是C++标准库中的动态数组,大小可以动态调整。元素访问:1.普通数组和array:使用索......
  • C++ 泛型编程之可变参数包
    C++泛型编程之可变模板参数·variadictemplates可以表示0到任意个数、任意类型的参数1.可变模板参数的展开:template<typename...Args> //可以将参数包展开一个个独立的参数voidfunc(Args...args); //声明一个参数包Args...args这个参数包可以包括0到任意个模板参数......
  • 【Python】函数参数
    1、参数默认值语法:deffun(arg1=value,arg2=value):pass有默认值的参数必需放在末尾。2、可变参数语法:deffun(*args):pass可变参数必需放在末尾。args在函数内部是一个元组。3、关键字参数语法:deffun(**args):pass关键字参数必需放在末尾,args在函......