c++ - std::accumulate 中的无效转换

标签 c++ c++11 accumulate stdarray

我有一个类表示 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/

相关文章:

c++ - 在 C++ 中计算两个 vector 的标量积

c++ - 在 C++11 之后的现代 C++ 中使用原始指针

c++11 - 为什么带有shared_ptr的atomic_load不能用gcc 4.9编译?

string - C++11:如何使用accumulate/lambda函数计算字符串向量中所有大小的总和?

python - 列表的累积乘积

r - 如何在数据帧计算中用矢量函数替换 R 中的 for 循环?

c++ - 为什么这个程序的输出是意外的?

c++ - C/C++ 从根位置搜索文件夹并返回绝对路径

c++ - 线程安全游戏引擎 : Multi-Threading Best Practices?

c++ - (Im) 使用可变参数模板完美转发