写一般的最小函数,我想到了两个问题.代码适用于任何输入类型和不同的参数号:
namespace xyz
{
template <typename T1, typename T2>
auto min(const T1 &a, const T2 &b) -> decltype(a+b)
{
return a < b ? a : b;
}
template <typename T1, typename T2, typename ... Args>
auto min(const T1 &a, const T2 &b, Args ... args) -> decltype(a+b)
{
return min(min(a, b), args...);
}
}
int main()
{
cout << xyz::min(4, 5.8f, 3, 1.8, 3, 1.1, 9) << endl;
// ^ ^ ^
// | | |
// float double int
}
Run Code Online (Sandbox Code Playgroud)
有更好的替代品decltype(a+b)
吗?我认为有一个我不记得的标准课,类似于decltype(std::THE_RESULT<a,b>::type)
.
返回的类型decltype(std::THE_RESULT<a,b>::type)
是const &
不是?
BoB*_*ish 13
std::common_type
(c++11
):
对于非专门
std::common_type
的规则来确定每对之间的常见的类型T1
,T2
是完全确定三元条件运算符的返回类型,其中的规则T1
和T2
在本类型的第二和第三运算数的.
和
对于算术类型,公共类型也可以被视为(可能是混合模式)算术表达式的类型,例如
T0() + T1() + ... + Tn().
不确定const&
,但你可以玩std::remove_cv
和std::remove_reference
(并std::is_reference
找出答案).
实际上,这是一个类型支持实用程序列表.把自己打昏.
在答案和值得评论后,我做了如下:
template <typename T1, typename T2>
auto min(const T1 &a, const T2 &b)
-> typename std::common_type<const T1&, const T2&>::type
{
return a < b ? a : b;
}
template <typename T1, typename T2, typename ... Args>
auto min(const T1 &a, const T2 &b, const Args& ... args)
-> typename std::common_type<const T1&, const T2&, const Args& ...>::type
{
return min(min(a, b), args...);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1286 次 |
最近记录: |