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 時,你需要小心類型安全和類型轉換。
首先,包括 <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++ 中返回不同類型的方法,你可以根據具體需求選擇其中之一。
本文鏈接:http://www.www897cc.com/showinfo-26-69005-0.html你知道C++如何在一個函數內返回不同類型嗎?
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com