c++ - 创建一个可能返回也可能不返回值的仿函数/lambda 的包装器

标签 c++ c++11 lambda functor

我有以下仿函数,它包装了另一个仿函数或 lambda 函数并自动设置索引参数。一个例子将解释得最好。我可以执行以下操作:

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

输出:

5 0
3 1
9 2

这是仿函数代码:

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);
}

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

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

但是我不知道如何修改我的仿函数来让它工作。我希望仿函数与返回值的函数和不自动返回值的函数兼容。

谁能提供一些建议? 谢谢!

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

最佳答案

您必须更改您的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++);
}

关于c++ - 创建一个可能返回也可能不返回值的仿函数/lambda 的包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18048602/

相关文章:

C++ - 链表不生成任何输出

c++ - 子 vector 修改原始 vector

c++ - "position"是 C++ 中的保留字吗?

C++0x 原子模板实现

c++ lambda,无法访问拷贝捕获的变量

c++ - 错误 'extern' 及更高版本 'static'

c++ - 为什么 C++11 'auto' 关键字对静态成员不起作用?

c++ - 从 std::function 的 vector 中移除一个项目

java - 使用函数式 java 快速失败(或者更确切地说,返回)

java - lambda 表达式和全局变量