I am having problems passing lambda expressions as a parameter to a method of a template class.
If I compile the following code:
main.cpp:
#include "a.h"
int main(int argc, char** argv) {
A<int> o;
o.a([&](){ });
}
a.h:
template <typename T>
class A {
public:
template <typename Lambda>
void a(const Lambda& f) {
f();
}
};
It works fine.
However I do not want to have my implementation of class A in a.h, I want to put the code it in a separate cpp file. So I now have
main.cpp:
Unchanged
a.h:
template <typename T>
class A {
public:
template <typename Lambda>
void a(const Lambda& f);
};
a.cpp:
#include "a.h"
template <typename T>
template <typename Lambda>
void A<T>::a(const Lambda& f) {
f();
}
template class A<int>;
I now get the following error:
In file included from test.cpp:1:0:
a.h:7:7: error: 'void A<T>::a(const Lambda&) [with Lambda = main(int, char**)::__lambda0; T = int]', declared using local type 'const main(int, char**)::__lambda0', is used but never defined [-fpermissive]
void a(const Lambda& f);
^
Why is that? How can I fix it?
I noticed if I put everything in the same cpp file, it works. The problem only occurs when I want to split it this way which is necessary to keep my code organized.
Thank you for your answer
This is very strange because even this works:
main.cpp
#include "a.h"
int main(int argc, char** argv) {
A<int> o;
o.a([&](){ });
}
template <typename T>
template <typename Lambda>
void A<T>::a(const Lambda& f) {
f();
}
template class A<int>;
a.h
template <typename T>
class A {
public:
template <typename Lambda>
void a(const Lambda& f);
};
This works. For some reason, It just won't work when I separate the main() and the method implementation in two distinct cpp files.
Why?