你知道C++如何在一個(gè)函數(shù)內(nèi)返回不同類型嗎?
方法一:使用 std::variant
std::variant 允許你在一個(gè)函數(shù)內(nèi)返回不同類型的值,但它要求所有可能的返回類型都在一個(gè)有限的集合中,你需要提前定義這個(gè)集合。
首先,包括 <variant> 頭文件:
#include <variant>
然后,使用 std::variant 來定義函數(shù)的返回類型:
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!";
}
}
在這個(gè)示例中,GetDifferentValue 函數(shù)可以返回 int、double 或 std::string,具體返回哪種類型取決于 choice 參數(shù)的值。
方法二:使用 std::any
std::any 允許你在一個(gè)函數(shù)內(nèi)返回不同類型的值,而無需提前定義可能的返回類型。但在使用 std::any 時(shí),你需要小心類型安全和類型轉(zhuǎn)換。
首先,包括 <any> 頭文件:
#include <any>
然后,使用 std::any 來定義函數(shù)的返回類型:
std::any GetDifferentValue(int choice) {
if (choice == 0) {
return 42;
} else if (choice == 1) {
return 3.14;
} else {
return "Hello, World!";
}
}
在這個(gè)示例中,GetDifferentValue 函數(shù)可以返回任何類型的值。
方法三:使用模板和多態(tài)
另一種方式是使用模板和多態(tài),這樣你可以在運(yùn)行時(shí)動(dòng)態(tài)確定返回的類型。這通常需要?jiǎng)?chuàng)建一個(gè)基類,派生出具體類型的子類,并使用基類指針或智能指針進(jìn)行返回。
#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;
}
在這個(gè)示例中,GetDifferentValue 返回一個(gè)指向 Base 基類的智能指針,而 Base 有多個(gè)派生類,代表不同的返回類型。
以上是三種在 C++ 中返回不同類型的方法,你可以根據(jù)具體需求選擇其中之一。