Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No possibility of default lambda in class template

Tags:

c++

templates

I've found out that one cannot create a working template class that has a default nothing-doing std::function in it, however if we create non-template class, there is no problem with the default value. Default lambda has no captures. Please see:

struct Dump {
    function<void(bool)> f = [](bool) {};
};

int main() {
    Dump a;
    a.f(true);
}

The above example works, however when parameterized (even parameter is not used)

template <class T>
struct Dump {
    function<void(bool)> f = [](bool) {};
};


int main() {
    Dump<bool> a;
    a.f(true);
}

during compilation get an error:

error: conversion from 'Dump<bool>::__lambda0' to non-scalar type 'std::function<void(bool)>' requested
note: synthesized method 'constexpr Dump<bool>::Dump()' first required here 
like image 856
pawel_j Avatar asked Aug 07 '18 12:08

pawel_j


1 Answers

It seems that older versions of compilers (close to when C++ 11 introduced these features) have some issues compiling this code, but they look like compiler bugs. You can play with different compiler versions here.

  • clang has no problems with the code since version 3.4.1 (around the time C++ 11 became a thing).

  • gcc gives the error you show in versions 4.7.1 to 4.9.0, compiles it just fine in 4.9.1 to 4.9.4, gets an internal compiler error (!) in 5.1 and apparently has no problem with it afterwards.

  • icc version 13.0.1 rejects the initializer altogether, 16.0.1 and later has no problem.

  • MSVC only has two versions available and starts from the 2015 version but eats the syntax without problems.

So the solution for you would be to either avoid default-initialization of std::function with lambdas or simply use a more recent compiler. The latter will probably save you a lot of pain in the long run.

like image 108
Max Langhof Avatar answered Oct 24 '22 19:10

Max Langhof