【问题标题】:Create a wrapper of a functor/lambda which may or may not return a value创建一个函子/lambda 的包装器,它可能会或可能不会返回一个值
【发布时间】:2013-08-05 14:17:58
【问题描述】:

我有以下函子,它包装了另一个函子或 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++ Compiler Nov 2012 CTP

【问题讨论】:

    标签: c++ c++11 lambda functor


    【解决方案1】:

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

    【讨论】:

    • 你在我之前修好了吗
    • 错误 C2893: 无法专门化函数模板 'unknown-type stx::IndexFunctor<:board::newgame::>>::operator ()(Args &&...) ' 1> 使用以下模板参数:1> 'int'
    • 我正在使用 VS2012 和 Microsoft Visual C++ 编译器 2012 年 11 月 CTP
    • @Neil:CTP 中有十亿个可变参数模板错误。如果代码不起作用,我会先尝试使用其他一些编译器,然后再假设代码错误。
    • 您能否解释一下 std::forward 的使用以及为什么 index++ 两次,请在您的回答中解释一下?
    猜你喜欢
    • 2018-12-07
    • 1970-01-01
    • 2023-02-17
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    • 2013-12-20
    相关资源
    最近更新 更多