首页 > 解决方案 > 编写一个函数,通过判断每个参数的类型自动确定返回值

问题描述

标头中的max()函数<algorithm>不支持不同数据类型的两个参数。因此,我尝试使用templateand#if和宏编写自己的代码。到目前为止我的代码:#else#endif

#include <iostream>

template <class type1, class type2>
#if sizeof(type1) >= sizeof(type2)
    type1 max(type1 a, type2 b){
        return (a > b) ? a : b;
    }
#else
    type2 max(type1, type2){
        return (a > b) ? a : b;
    }
#endif

int main(){
    int a, d; long long b, c;
    std::cin >> a >> b;
    std::cout << "The max is " << max(a, b) << ".\n";
    std::cin >> c >> d;
    std::cout << "The max is " << max(c, d) << ".\n";
    return 0;
}

现在显然代码无效,因为它引发了语法错误(也许我误解了这些宏的工作方式,因为我对这个主题以及模板都是新手):

|Line 05 | error: missing binary operator before token "type1"    |
|        | In function 'type2 max(type1, type2)':                 |
|Line 11 | error: 'a' was not declared in this scope              |
|Line 11 | error: 'b' was not declared in this scope              |

我想知道是否可以构建这样的程序以及如何构建。

标签: c++templatesmacros

解决方案


您不能将宏与这样的模板混合使用;宏将首先被评估,并且不会像您预期的那样与模板交互。

您可以使用std::conditional显式声明返回类型,

// if sizeof(type1) >= sizeof(type2), then declare the return type as type1
// otherwise type2
template <class type1, class type2>
std::conditional_t<sizeof(type1) >= sizeof(type2), type1, type2>
max(type1 a, type2 b) {
    return (a > b) ? a : b;
}

或者你可以只使用auto. 返回类型将自动推断为由条件运算符确定的通用类型。对于max(int, long long)and max(long long, int),返回类型将是long long,与上述版本相同。(请注意,通用类型可能与上述版本不同;例如,max(short, bool)返回类型将int代替short.)

template <class type1, class type2>
auto max(type1 a, type2 b) {
    return (a > b) ? a : b;
}

居住


推荐阅读