我正在尝试编写一个通用函数,它将输入作为uint8
、uint16
、uint32
、uint64
, ....并以最大元素的数据类型返回最大值?
例如:
template < typename T, typename X>
auto Max_Number(T valueA, X valueB)
{
if (valueA > valueB)
return valueA;
else
return valueB;
}
P.S:此示例假设最大元素属于最大数据类型。
最佳答案
返回类型必须在编译时确定。您可以使用std::common_type
(自 C++11 起):
For arithmetic types not subject to promotion, the common type may be viewed as the type of the (possibly mixed-mode) arithmetic expression such as
T0() + T1() + ... + Tn()
.
template < typename T, typename X>
typename std::common_type<T, X>::type Max_Number ( T valueA, X valueB ) {
...
}
或者使用std::conditional
(自 C++11 起)将返回类型声明为大类型(其 sizeof
更大)。
template < typename T, typename X>
typename std::conditional<sizeof(T) >= sizeof(X), T, X>::type Max_Number ( T valueA, X valueB ) {
...
}
请注意,对于这种情况,如果 T
和 X
具有相同的大小,则 T
将始终用作返回类型。如果你想更精确地控制它,你可以使用一些特征来指定确切的类型。
关于c++ - 我们可以有一个具有多种返回类型的函数吗? (C++11 及以上版本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57951456/