【问题标题】:Lambda as default parameter to a member function templateLambda 作为成员函数模板的默认参数
【发布时间】:2014-08-25 16:51:15
【问题描述】:

头文件

#include <functional>

struct Check {};
struct Entry {};
struct Table {};

class SeatEntries
{
public:
    // does not compile!
    template<class T>
    void Populate(T from,
                  std::function<bool (Entry *)> predicate = [] (Entry *) { return true; },
                  std::function<void (Entry *)> action = [] (Entry *) {})
    {
        Reset();
        PopulateImpl(from, predicate, action);
    }

    // compiles!
    void PopulateFromCheck(Check *from,
                  std::function<bool (Entry *)> predicate = [] (Entry *) { return true; },
                  std::function<void (Entry *)> action = [] (Entry *) {})
    {
        Reset();
        //PopulateImpl(from, predicate, action);
    }

    void Reset();

private:
    template<class T>
    void PopulateImpl(T from,
                      std::function<bool (Entry *)> predicate,
                      std::function<void (Entry *)> action);
};

template<>
void SeatEntries::PopulateImpl<Table *>(Table *from, std::function<bool (Entry *)> predicate, std::function<void (Entry *)> action);

template<>
void SeatEntries::PopulateImpl<Check *>(Check *from, std::function<bool (Entry *)> predicate, std::function<void (Entry *)> action);

问题

为什么第一个成员函数模板不编译?这是 VS2012 和 gcc 4.8.1 中的错误吗?我是否对有关成员函数模板和 lambdas 作为默认参数的一些事实一无所知?

VS2012 输出

error C2958: the left parenthesis '(' found at 'seathelpers.h(33)' was not matched correctly  
error C2988: unrecognizable template declaration/definition  
error C2059: syntax error : '{'  
error C2334: unexpected token(s) preceding '{'; skipping apparent function body  

引用的左括号是 Populate() 函数模板的左括号。

GCC 4.8.1 (MinGW)

Test.h:13:66: internal compiler error: in push_class_level_binding_1, at cp/name-lookup.c:3019  
    std::function<bool (Entry *)> predicate = [] (Entry *) { return true; },  
                                               ^

【问题讨论】:

  • 一个ICE 编译器错误的结果。是的,g++4.8.1 中有已知的错误,其中 lambdas 作为默认参数。 clang++ 不会抱怨这段代码。
  • 检查bug tracker或更新你的编译器。
  • @dyp 谢谢,我应该阅读 gcc 的全部输出。因为VS2012无法编译,所以我匆忙在gcc中测试了它。确实已经针对这种情况提交了错误报告。

标签: c++ templates c++11 lambda default-parameters


【解决方案1】:

我能够使用 gcc 4.8.3 编译上述代码,没有错误

$ g++ --version
g++ (GCC) 4.8.3 20140624 (Red Hat 4.8.3-1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 2015-01-15
    • 2016-06-25
    • 1970-01-01
    • 2023-04-02
    相关资源
    最近更新 更多