【发布时间】:2015-03-04 04:19:19
【问题描述】:
我有一个类代表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 实现与我的构造函数不兼容的问题吗?
【问题讨论】:
-
可变参数构造函数正在劫持复制构造函数调用。约束它。
-
@T.C.这很有意义。如何约束它?
-
@Amxx 隐式指定复制构造函数:
Point(const Point &) = default; -
T.C.说是对的。转发引用为复制ctor调用产生了更好的匹配,因此它被重载决议选择。仍然为此类生成 Copy-ctor。它不必显式默认(用户声明)
-
你在重复计算
array[0]。如果您使用array[0]作为初始值,则从array+1开始累积。或者,使用Point<float,3>(0,0,0)作为初始值。
标签: c++ c++11 accumulate stdarray