gpt4 book ai didi

c++ - 返回未知类型的函数

转载 作者:可可西里 更新时间:2023-11-01 16:52:20 27 4
gpt4 key购买 nike

class Test
{
public:

SOMETHING DoIt(int a)
{
float FLOAT = 1.2;
int INT = 2;
char CHAR = 'a';

switch(a)
{
case 1: return INT;
case 2: return FLOAT;
case 3: return CHAR;
}
}
};


int main(int argc, char* argv[])
{
Test obj;
cout<<obj.DoIt(1);
return 0;
}

现在,使用 a = 1 意味着我需要返回一个整数等知识,Doit() 是否可以返回可变数据类型的变量?

本质上,我应该用什么替换 SOMETHING

PS:我正在尝试寻找一种替代方法来返回包含这些数据类型的结构/union 。

最佳答案

您可以使用 boost::anyboost::variant做你想做的事。我推荐 boost::variant,因为您知道要返回的类型集合。


这是一个非常简单的示例,但您可以使用 variant 做更多的事情。查看引用以获取更多示例:)

#include "boost/variant.hpp"
#include <iostream>

typedef boost::variant<char, int, double> myvariant;

myvariant fun(int value)
{
if(value == 0)
{
return 1001;
}
else if(value == 1)
{
return 3.2;
}
return 'V';
}

int main()
{
myvariant v = fun(0);
std::cout << v << std::endl;

v = fun(1);
std::cout << v << std::endl;

v = fun(54151);
std::cout << v << std::endl;
}

输出:

1001
3.2
V

我会使用 boost::variant 而不是 union 因为你不能在 union 中使用非 POD 类型。此外,如果您不知道要处理的类型,boost::any 非常有用。否则,我会使用 boost::variant,因为它更高效、更安全。


回答已编辑的问题:如果您不想随代码一起提供 Boost,请查看 bcp .来自同一链接的 bcp 的描述:

The bcp utility is a tool for extracting subsets of Boost, it's useful for Boost authors who want to distribute their library separately from Boost, and for Boost users who want to distribute a subset of Boost with their application.

bcp can also report on which parts of Boost your code is dependent on, and what licences are used by those dependencies.

关于c++ - 返回未知类型的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1358427/

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