我正在尝试创建一个函数,该函数将任意函子应用于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
?