我试图创建适用任意函子F
到所提供的元组的每个元素的功能:错误:使用删除的功能。为什么?
#include <functional>
#include <tuple>
// apply a functor to every element of a tuple
namespace Detail {
template <std::size_t i, typename Tuple, typename F>
typename std::enable_if<i != std::tuple_size<Tuple>::value>::type
ForEachTupleImpl(Tuple& t, F& f)
{
f(std::get<i>(t));
ForEachTupleImpl<i+1>(t, f);
}
template <std::size_t i, typename Tuple, typename F>
typename std::enable_if<i == std::tuple_size<Tuple>::value>::type
ForEachTupleImpl(Tuple& t, F& f)
{
}
}
template <typename Tuple, typename F>
void ForEachTuple(Tuple& t, F& f)
{
Detail::ForEachTupleImpl<0>(t, f);
}
struct A
{
A() : a(0) {}
A(A& a) = delete;
A(const A& a) = delete;
int a;
};
int main()
{
// create a tuple of types and initialise them with zeros
using T = std::tuple<A, A, A>;
T t;
// creator a simple function object that increments the objects member
struct F
{
void operator()(A& a) const { a.a++; }
} f;
// if this works I should end up with a tuple of A's with members equal to 1
ForEachTuple(t, f);
return 0;
}
直播的代码示例:http://ideone.com/b8nLCy
我不希望创建的A
因为副本它可能是昂贵的(显然在这个例子中它不是),所以我删除了拷贝构造函数。当我运行上面的程序我得到:
/usr/include/c++/4.8/tuple:134:25: error: use of deleted function ‘A::A(const A&)’ : _M_head_impl(__h) { }
我知道构造函数被删除(这是故意的),但我不明白的是为什么它试图让我的结构的副本。为什么会发生这种情况,如何在不复制A
的情况下实现这一目标?
是不是有一种调用堆栈显示试图使用元组副本构造函数? – 2014-11-05 04:07:19
由于这是一个与助推相关的问题,我建议添加boost标签。 – 2014-11-05 04:07:23
@ D'Nabre:真的不是。这是一个关于为什么'std :: tuple'试图首先复制它的成员的问题。 – 2014-11-05 04:08:00