Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda function as a default argument for std::function in constructor

I'd like to have a default functor for a functor parameter in the constructor of a class. As a minimal example I came up with a class which should server as a filter, which filters elements of type T iif a filter function returns true. The filter function should be provided in the constructor, defaulting to an "accept all" filter function:

template<class T>
class Filter
{
public:
    typedef std::function<bool(const T&)> FilterFunc;

    Filter(const FilterFunc & f = [](const T&){ return true; }) :
        f(f)
    {
    }

private:
    FilterFunc f;
};

I instantiate the template class like the following:

int main() {
    Filter<int> someInstance;  // No filter function provided    (<-- line 19)
}

However, gcc 4.7 doesn't seem to like this piece of code:

prog.cpp: In constructor ‘Filter<T>::Filter(const FilterFunc&) [with T = int; Filter<T>::FilterFunc = std::function<bool(const int&)>]’:
prog.cpp:19:17: internal compiler error: in tsubst_copy, at cp/pt.c:12141
Please submit a full bug report,
with preprocessed source if appropriate.
See <file:///usr/share/doc/gcc-4.7/README.Bugs> for instructions.
Preprocessed source stored into /home/g9i3n9/cc82xcqE.out file, please attach this to your bugreport.

What's wrong? Is my code standard conformant (so GCC is really buggy here or hasn't implemented this) or am I doing something wrong?

As a workaround, I currently use a default-constructed std::function and only call it (where I want to call it) if it was set:

    Filter(const FilterFunc & f = FilterFunc) :
        f(f)
    {
    }

    // When using it:
    void process() {
        if (!f || f(someItem)) {    // <-- workaround
        }
    }
like image 869
leemes Avatar asked Oct 22 '22 14:10

leemes


1 Answers

This is a bug: the compiler crashed or a fatal internal error occurred while processing the source code, and the message itself is kindly inviting you to treat the error as such:

"Please submit a full bug report, with preprocessed source if appropriate."

Here is another possible workaround:

template<class T>
class Filter
{
public:
    typedef std::function<bool(const T&)> FilterFunc;

    Filter() { }
    Filter(FilterFunc const& f) : f(f) { }

private:
    FilterFunc f = [](const T&){ return true; };
};

As a further alternative, GCC supports delegating constructors, which you may want to consider:

#include <functional>

template<class T>
class Filter
{
public:
    typedef std::function<bool(const T&)> FilterFunc;

    Filter() : Filter([](const T&){ return true; }) { }
    Filter(FilterFunc const& f) : f(f) { }

private:
    FilterFunc f;
};
like image 51
Andy Prowl Avatar answered Nov 02 '22 10:11

Andy Prowl