首页 > 解决方案 > C++ 函数返回不同的类型

问题描述

我试图创建一个函数,该函数根据参数返回值,如下所示:

type getValue(string input) return <OUTPUT>

OUTPUT的类型将根据输入的内容更改为int, string,bool等。我得到了排序,但我一直遇到的问题是返回类型。我试过autotype 但我得到的只是这个错误:

错误:'auto' 的推导不一致:'int' 然后是 'char'

一遍又一遍地使用此函数可以输出的每种类型。我不会做模板,因为你必须这样做

getValue<type>(input);

而且我无法猜测输出以放入模板类型。我已经使用了很多我可以做的选项,但它太复杂了。

标签: c++

解决方案


正如评论所指出的,您需要使用std::variantorstd::any作为返回类型。

std::any getValue(string input) {
    if (input == ...) {
        return "string return type";
    }
    if (input == ...) {
        return 100;
    }
    if (input == ...) {
        return 123.456;
    }

    return false;
}

但是,如果您只能生成一小组返回类型,请考虑使用变体,因为它会受到更多限制:

// assuming these are the only 4 types you can return
using getValueReturnType = std::variant<std::string, int, double, bool>;

// The function definition would be exactly the same as above with std::any
getValueReturnType getValue(string input);

推荐阅读