I'm trying to create the following class that I can use to test objects to see if they pass some filter.
template <typename T>
class Filter
{
public:
typedef bool (*Functor)(const T&);
bool test(const T& t) {
return func(t);
}
void setTester(Functor f) {
func = f;
}
private:
Functor func;
};
If I just create a method in the global namespace this works fine.
bool testFunc(const Object& obj)
{
return !obj.name().isEmpty();
}
void foo(const Object& obj)
{
Filter<Object> filter;
filter.setTester(testFunc);
filter.test(obj);
}
But what I'd really like is to use lambda functions so that I don't have to create all of my filter methods like this. I want to be able to create them on the fly.
void foo(const Object& object)
{
Filter<Object> filter;
filter.setTester([](const Object& object) {
return !object.name().isEmpty();
});
filter.test(object);
}
But when I do this I get the following compile error.
C2664: 'ov::Filter<T>::setTester' : cannot convert parameter 1 from 'ov::`anonymous-namespace'::<lambda0>' to 'bool (__cdecl *)(const T &)'
with
[
T=ov::Object
]
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
I've read other posts about passing lambda functions as function pointers like this one and I understand that they cannot capture in order for this to work. That's fine, and you can see I'm not trying to capture anything.
I am compiling my code using VS2010.
So what am I doing wrong?