gpt4 book ai didi

c++ - 存储多种类型并根据请求返回单一类型

转载 作者:行者123 更新时间:2023-11-30 03:36:44 25 4
gpt4 key购买 nike

我需要创建一个存储多个用户定义类型的类。它应该按需返回其中之一。有没有办法实现一个函数返回所有类型?

请注意:我无法使用 Boost 库。我需要在 Visual Studio 中实现

class One {};
class Two {};
class Three {};

enum Type
{
OneType,
TwoType,
ThreeType
};
class GenericType
{
template <typename T> // --- How to implement this function
T getValue(Type type)
{
switch(type)
{
case One: return oneType; // Error
case Two: return twoType;
case Three: return threeType;
}
}
shared_ptr<OneType> oneType;
shared_ptr<TwoType> twoType;
shared_ptr<ThreeType> threeType;
Type m_type;
};

最佳答案

在 C++11 中你有一个 std::tuple完成这项工作的类(class)。您可以使用 std::get 检索所需的元素,如下所示:

// Create a tuple
std::tuple<std::shared_ptr<OneType>, std::shared_ptr<TwoType>> tuple{null, null};
// Get element
std::get<std::shared_ptr<OneType>>(tuple)

关于c++ - 存储多种类型并根据请求返回单一类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40552253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com