【问题标题】:Template C++0x lambda function... or functor/predicate?模板 C++0x lambda 函数...或仿函数/谓词?
【发布时间】:2011-03-13 13:59:50
【问题描述】:

我最近升级了我的g++,所以我可以享受 lambda 函数。 一切都很棒,我非常感谢那些让 C++ 和 gcc 成为可能的人。只有一件事我似乎无法解决 - 如何将 lambda 的参数模板化?下面是 lambda 用法的基本示例来演示该问题。

示例 #1,一切都很美味:

#include <cstdio>

struct bar {
    bar () {}

    void say () {
        printf ("bar::say()\n");
    }

    void say () const {
        printf ("bar::say() const\n");
    }
};

template <typename T>
void do_work (const T & pred) {
    bar b;
    pred (b);
}

int main () {
    do_work ([] (bar & b) { b.say (); });
}

现在,假设do_work 现在使用不同的参数类型调用谓词两次。所以这里是例子#2:

#include <cstdio>

struct foo {
    foo () {}

    void say () {
        printf ("foo::say()\n");
    }

    void say () const {
        printf ("foo::say() const\n");
    }
};

struct bar {
    bar () {}

    void say () {
        printf ("bar::say()\n");
    }

    void say () const {
        printf ("bar::say() const\n");
    }
};

template <typename T>
void do_work (const T & pred) {
    const foo f;
    bar b;
    pred (f);
    pred (b);
}

int main () {
    do_work ([] (auto & b) { b.say (); });
}

注意auto 关键字。我还尝试就地对其进行模板化。不要试图用 gcc 编译它,这是我得到的:

./test.cpp:31:5: internal compiler error: Segmentation fault
Please submit a full bug report,
with preprocessed source if appropriate.
See <http://gcc.gnu.org/bugs.html> for instructions.

但你明白了。理论上,我可以用新的函数声明风格来解决它,但这不是重点。这是我真正想要做的,但使用了简化的语法(为简单起见,foobardo_work 被剥离):

struct pred_t {
    pred_t () = default;

    template <typename T>
    void operator () (T && obj) const {
        obj.say ();
    }
};

int main () {
    do_work (pred_t ());
}

有没有办法,或者至少计划,添加对不完全专用的 lambda 函数的支持,以便它们的行为类似于 template &lt;typename T&gt; operator () (T &amp;&amp;) 的谓词?我什至不知道如何命名它,也许是 lambda 谓词?请让我知道你的想法!谢谢!

【问题讨论】:

    标签: c++ templates c++11 lambda


    【解决方案1】:

    这些被讨论为“多态 lambdas”,并被拒绝,因为它对概念提案产生了问题。

    去年2009 at the Frankfurt meeting,概念提案被否决,但C++0x 不再考虑多态lambda。

    C++0x and the Lack of Polymorphic Lambdas

    【讨论】:

      【解决方案2】:
      do_work ([] (auto & b) { b.say (); });
      

      我认为auto 关键字在函数/lambda 参数中是不允许的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-18
        • 1970-01-01
        • 2019-11-13
        • 2018-11-12
        • 1970-01-01
        相关资源
        最近更新 更多