返回string,float或int的C ++函数

问题描述 投票:-2回答:2

所以我简化了我在这里尝试做的事情,但基本上我有一个看起来像这样的函数:

int perform_operation(int left, std::string op, int right) {
    if (op == "+")
        return left + right;
    if (op == "-")
        return left - right;

    ... 

};

我希望这个函数能够将floatintstring作为左右参数。如果传入字符串并使用+运算符,则应该连接字符串,如果运算符不支持字符串,则应该抛出错误。

我也希望该函数能够返回floatintstring

也许这是不可能的,如果是这样,请给我一个关于如何做到这一点的建议。

...

如果有人在想,我正在写一名翻译。

c++ g++
2个回答
3
投票

您可以使用功能模板实现此目的。

template<class T>
T perform_operation(const T& left, std::string_view op, const T& right)
{
    if (op == "+")
        return left + right;
    if (op == "-")
        return left - right;

    // ...
}

现在由于std::string不支持operator -并且您希望操作引发错误,因此您需要专门化此类型的模板:

template<>
std::string perform_operation<std::string>(const std::string& left, std::string_view op, const std::string& right)
{
    if (op == "+")
        return left + right;

    throw std::invalid_argument("std::string supports operator + only");
}

这可以像下面这样实例化和调用。

const int result1 = perform_operation(1, "+", 2);
const float result2 = perform_operation(2.f, "-", 3.f);
const std::string result3 = perform_operation<std::string>("hello", "+", " world");

assert(result1 == 3);
assert(std::abs(result2 + 1.0f) < std::numeric_limits<float>::epsilon()));
assert(result3 == "hello world");

请注意,我已将参数类型更改为接受操作数作为const限定引用,操作符作为std::string_view(C ++ 17特性),但后者不是必需的。


1
投票

不确定为什么这个问题被低估了,因为这在C ++中非常有意义。

你需要的是一个template。具体来说,是功能模板。

template <typename T>
T perform_operation(T left, std::string op, T right) {
    if (op == "+")
        return left + right;
    if (op == "-")
        return left - right;
    // ... 
}

当然,模板没有operator-,所以你可以使用重载:

std::string perform_operation(std::string left, std::string op, std::string right) {
    if (op == "+")
        return left + right;
   // ...
}
© www.soinside.com 2019 - 2024. All rights reserved.