【发布时间】:2016-06-19 16:04:09
【问题描述】:
我有以下sn-p的代码:
#include <type_traits>
#include <limits>
#include <initializer_list>
#include <cassert>
template <typename F, typename... FIn>
auto min_on(F f, const FIn&... v) -> typename std::common_type<FIn...>::type
{
using rettype = typename std::common_type<FIn...>::type;
rettype result = std::numeric_limits<rettype>::max();
(void)std::initializer_list<int>{((f(v) < result) ? (result = static_cast<rettype>(v), 0) : 0)...};
return result;
}
int main()
{
auto mod2 = [](int a)
{
return a % 2;
};
assert(min_on(mod2, 2) == 2); // PASSES as it should
assert(min_on(mod2, 3) == 3); // PASSES as it should
assert(min_on(mod2, 2, 3) == 3); // PASSES but shouldn't - should be 2
assert(min_on(mod2, 2, 3) == 2); // FAILS but shouldn't - should be 2
}
模板函数 min_on 背后的想法是,它应该从传递给它的参数列表中返回参数 x v,以便它为表达式 f(v) 提供最小值。
我观察到的问题是,不知何故,std::initializer_list 中的参数顺序很重要,因此上面的代码将失败,而这段代码:
assert(min_on(mod2, 3, 2) == 2);
会起作用。这里可能有什么问题?
【问题讨论】:
标签: c++ c++11 lambda initializer-list typetraits