错误:使用已删除的功能.为什么?

qua*_*ant 1 c++ c++11 gcc4.8

我正在尝试创建一个函数,将任意仿函数应用于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;
}
Run Code Online (Sandbox Code Playgroud)

实时代码示例: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) { }
Run Code Online (Sandbox Code Playgroud)

我知道构造函数被删除(这是故意的),但我不明白是为什么它试图复制我的结构.为什么会发生这种情况,如何在不复制的情况下实现这一目标A

Ben*_*igt 7

这是您收到"已删除的构造函数"错误的问题:

std::function<void(A)> f = [](A& a) { a.a++; };
Run Code Online (Sandbox Code Playgroud)

您正在尝试设置std::function一个A按值传递的值.但是A,没有copy-constructor,不能通过值传递.

尝试更仔细地匹配实际参数类型:

std::function<void(A&)> f = [](A& a) { a.a++; };
Run Code Online (Sandbox Code Playgroud)

但是既然你没有捕获变量,你可以试试

void(*f)(A&) = [](A& a) { a.a++; };
Run Code Online (Sandbox Code Playgroud)

你的模板递归的基本情况也遇到了一个主要问题:即使你开始enable_if工作,它似乎也没有,你会有一个模糊的调用.我想你还需要禁用主案例.