我有一个类表示 N
维度中的一个点,带有一个 min
静态函数(逐个字段的最小值)
template<typename T, std::size_t N>
class Point : public std::array<T,N>
{
public:
template<typename... Args>
Point(Args&&... args) : std::array<T,N>{{args...}} {}
// ...
static Point min(const Point&, const Point&) {
// ...
}
};
我写的时候一切正常
Point<float,3> a = {0.f, 1.f, 2.f};
Point<float,3> b = {2.f, 1.f, 0.f};
Point<float,3> c = Point<float,3>::min(a,b); // OK
但是如果我尝试在数组上使用 std::accumulate
Point<float,3> array[100] = ... ;
Point<float,3> min = std::accumulate(array, array+100, array[0], Point<float,3>::min); // Error
我收到一个错误:
error: cannot convert ‘Point<float, 3ul>’ to ‘float’ in initialization
adimx::Point<T,N>::Point(Args&&... args) : std::array<T,N>{{args...}}
这是 std::accumulate
实现与我的构造函数不兼容的问题吗?
最佳答案
这是一种约束该构造函数的方法,以便它仅在所有参数都可以隐式转换为 float
时才参与重载决策:
template<bool... > class bool_pack;
template<bool... b>
using all_true = std::is_same<bool_pack<true, b...>, bool_pack<b..., true>>;
template<typename... Args,
class = typename std::enable_if<all_true<std::is_convertible<Args, float>::value...>::value>::type>
Point(Args&&... args) : std::array<T,N>{{args...}} {}
关于c++ - std::accumulate 中的无效转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28846602/