函数的多重返回类型 - C++

Lap*_*pys -1 c++ c++17

有没有办法(常规或没有)从函数中选择多个指定的返回类型.例如:

/* Concept code... */
class var {
    public:
        union {
            bool _bool;
            int _int;
            char* _char_pointer;
        } primitive_value;
        std::string type;

        var(bool arg) { primitive_value._bool = arg; type = "bool"; }
        var(int arg) { primitive_value._int = arg; type = "int"; }
        var(char* arg) { primitive_value._char_pointer = arg; type = "char*"; }

        // Function/ method that could return `bool`, `int` or `char*`
        <bool, int, char*> valueOf() const {
            if (type == "bool") return primitive_value._bool;
            else if (type == "int") return primitive_value._int;
            else if (type == "char*") return primitive_value._char_pointer;
        }
};
Run Code Online (Sandbox Code Playgroud)

还有一个类似的问题的引用在这里我已经看到了使用建议的void*指针或union的,但我还没有完全了解这些工作.

无容器类型(例如std::any,std::optional,std::variant)被允许,因为我想知道是否有对这些替代为好.

除此之外,这一切都是以好奇心为名.目前我正在搜索optionalvariant头文件,以了解我要求的功能是如何实现但到目前为止没有运气.

我希望这里的平台可以解决这个潜在的问题.

Mat*_*her 8

你可以混合使用模板函数和if constexpr(C++ 17):

template<typename T>
T valueOf() const {
    if constexpr(std::is_same<T, bool>) return _boolValueOf();
    else if constexpr(std::is_same<T, int>) return _intValueOf();
    else if constexpr(std::is_same<T, std::string>) return _std_stringValueOf();
}
Run Code Online (Sandbox Code Playgroud)

需要传递类型,但签名可能是:

template<typename T>
T valueOf(const T& d) const {
    if constexpr(std::is_same<T, bool>) return _boolValueOf(d);
    else if constexpr(std::is_same<T, int>) return _intValueOf(d);
    else if constexpr(std::is_same<T, std::string>) return _std_stringValueOf(d);
}
Run Code Online (Sandbox Code Playgroud)

  • 在方便的假设下,在编译时已知所请求的类型.在这种情况下,首先应该没有不同命名的函数在概念上做同样的事情.支持的类型应该有重载. (4认同)