I been trying to solve the next functional problem in C++:
template <typename T>
auto createFunction(T& ClosuredData) {
template <typename U>
return [&](function<void(T&, U&)> Callback) {
return [&](U& DataFromCallback) {
Callback(ClosuredData, DataFromCallback);
};
};
};
// example use
struct Person {
string name{"Foo"};
int age = 20;
}
Person foo{};
auto mutate = createFunction(foo);
auto changeAge = mutate<int>([](Person& person, int& age) {
person.age = age;
})
changeAge(20)
So basically a template Function creator with an inner template lambda. But of course as far as I know inner templates are not possible in C++. I tried to make the callback as an auto type, but of course that way I can't infer the DataFromCallback
resulting in false type-safety.
Can I somehow achieve a proper type safety without introducing a class/struct?
Edit: One of the "solution" I seen is using an auto type instead of a functional:
template <typename T>
auto CreateFunction(T& ClosuredData) {
return [&](auto Callback) {
return [&, Callback](auto DataFromCallback) {
Callback(ClosuredData, DataFromCallback);
};
};
};
This is really cool, but gives a false sense of typesafety, for example:
{
Person person{};
auto personMutator = CreateFunction(person);
auto changeAge = personMutator([](Person& person, int age) {
person.age = age;
});
changeAge(""); // Would not throw an error in this line, but at an upper stack
changeAge(any); // same stuff
}
It seems that you could use generic lambdas available since C++14 (which basically work as inner templates):
template <typename T>
auto CreateFunction(T& ClosuredData) {
return [&](auto Callback) {
return [&, Callback](auto DataFromCallback) {
Callback(ClosuredData, DataFromCallback);
};
};
};
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments