1

Why can I not get the template function to accept the lambda expression?

After searching high and low -- I seriously though that this would work, but this C++ code;

template <typename F> int proc(const F& lam)
{
    return lam();
}
void caller()
{
    int i = 42;
    int j = proc( [&i]()->int{ return i/7; } );
}

An I get the following errors;

$ g++ x.cc
x.cc: In function ‘void caller()’:
x.cc:11:44: warning: lambda expressions only available with -std=c++0x or -std=gnu++0x [enabled by default]
x.cc:11:46: error: no matching function for call to ‘proc(caller()::<lambda()>)’
x.cc:11:46: note: candidate is:
x.cc:3:27: note: template<class F> int proc(const F&)

I'm on linux using g++ 4.6.3 and 4.7.2

Does anybody know what I have to do to pass on a lambda expression as a parameter to a receiving template function? -- I don't want to use the std::function -- so my only alternative is to create an ugly functor pattern.

Update: Tried to declare the argument const F& lam, but without success. Update2: added call to compiler...

6
  • What flags are you passing to the compiler? Commented Sep 27, 2013 at 3:24
  • None -- no flags -- update question with call to compiler... Commented Sep 27, 2013 at 3:29
  • 1
    You have to use -std=c++11 with g++ 4.7.2 or -std=c++0x with g++ 4.6.3. Commented Sep 27, 2013 at 3:32
  • Thanks -- that does the trick -- now im very confuse what the warning message of "enabled by default" means ..... Commented Sep 27, 2013 at 3:34
  • See stackoverflow.com/q/13122636/951890 Commented Sep 27, 2013 at 3:36

1 Answer 1

3

Since the lambda isn't an lvalue, you need to pass it by const reference:

template <typename F> int proc(const F& lam)

Make sure to use -std=c++11 with g++ 4.7.2 or -std=c++0x with g++ 4.6.3.

Sign up to request clarification or add additional context in comments.

4 Comments

Unfortunately that did not solve the problem.. x.cc:11:46: error: no matching function for call to ‘proc(caller()::<lambda()>)’ x.cc:11:46: note: candidate is: x.cc:3:27: note: template<class F> int proc(const F&)
Thanks @Vaughn -- tried to cut-n-paste your working code -- still have same problem -- suspect it is a compiler version problem -- what version are you using?
@Soren: I'm using g++ 4.7.2
work with -std=c++11 with g++ 4.7.2 or -std=c++0x with g++ 4.6.3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.