创建一个functor/lambda的包装器,它可能会返回一个值,也可能不会返回一个值

Nei*_*irk 1 c++ lambda functor c++11

我有以下仿函数包装另一个仿函数或lambda函数并自动设置索引参数.一个例子将解释得最好.我可以做以下事情:

auto f = stx::with_index([](int a, int index){ std::cout << a << " " << index << std::endl; });
f(5);
f(3);
f(9);
Run Code Online (Sandbox Code Playgroud)

输出:

5 0
3 1
9 2
Run Code Online (Sandbox Code Playgroud)

这是仿函数代码:

template<class FUNC>
class IndexFunctor
{
public:
    typedef FUNC FUNC_T;

    explicit IndexFunctor(const FUNC_T& func) : func(func), index(0) {}

    template<class... ARGS>
    void operator ()(ARGS&&... args)
    {
        func(args..., index++);
    }

    const FUNC_T& GetFunctor() const
    {
        return func;
    }

    int GetIndex() const
    {
        return index;
    }

    void SetIndex(int index)
    {
        this->index = index;
    }

private:
    FUNC_T func;
    int index;
};

template<class FUNC>
IndexFunctor<FUNC> with_index(const FUNC& func)
{
    return IndexFunctor<FUNC>(func);
}
Run Code Online (Sandbox Code Playgroud)

现在的问题是我想将它与可能返回值的函数一起使用.例如

auto f = stx::with_index([](int a, int index){ return a * index; });
int a = f(5);
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚如何修改我的仿函数以使其工作.我希望仿函数与返回值的函数和不自动的函数兼容.

有人可以提供一些建议吗?谢谢!

我正在使用VS2012 Microsoft Visual C++编译器2012年11月CTP

Ton*_*ion 6

你必须改变你的operator()回报.

如果您使用的是C++ 11,则可以使用尾随返回类型.

template<typename... Args> 
auto operator ()(Args&&... args) 
-> decltype(func(std::forward<Args>(args)..., index++)) //get return type
{
    return func(std::forward<Args>(args)..., index++);
}
Run Code Online (Sandbox Code Playgroud)