So I've got a function like this:
template <typename T>
bool and_map(vector<T> v, function<bool(T)> fn) { ... }
And I want to pass it a vector and a lambda function like this:
[](int cell){ return(cell != -1); }
But I get an error which says there is no instance of and_map which takes these parameters.
When I do this it works:
template <typename T>
bool and_map(vector<T> v, function<bool(int)> fn) { ... }
How can I get it to work without specifying the parameter type of the passed function?
Here is the correct way to accept a functor:
template <typename T, typename F>
bool and_map(vector<T> v, F fn) { ... }
Having a function declared as:
template <typename T>
bool and_map(std::vector<T> v, std::function<bool(T)> fn)
a compiler tries to deduce a template type parameter T based on both arguments. However, a lambda expression is not std::function<T>, hence the compiler raises an error. To workaround that one can make the context of a second parameter (with std::function<bool(T)>) non-deducible with an identity trick:
template <typename T> struct identity { using type = T; };
template <typename T>
bool and_map(std::vector<T> v, typename identity<std::function<bool(T)>>::type fn)
{
return {};
}
std::vector<int> v;
and_map(v, [](int cell){ return(cell != -1); });
so that type T will be deduced only based on the first argument, and then used to define the type of the second parameter.
DEMO
Related
I have a complex problem that can be boiled down to the following deduction guide
template <class R> R return_r() { return R{}; }
void accep_float(float arg) { (void)arg; }
int main() {
accep_float(return_r());
}
Can I put a deduction guide to make the template deduct the right type according to the accepting function, like float here accep_float(return_type<float>());?
A templated conversion operator can be used for this kind of "backward" deduction:
struct foo {
template <typename T>
operator T() { return T{};}
};
void accep_float(float arg) { (void)arg; }
int main() {
accep_float(foo{});
}
I am not aware of deduction guides for function templates. Anyhow, you must first call foo{} (or return_r in your case) and only then the conversion to some argument type of accep_float can be done.
This pure backwards deduction is not possible, as far as I know. However, you can figure out the parameter types of any function beforehand, and use that to pass it in manually:
namespace detail {
template<typename R, typename... A>
constexpr auto parameter_types(R(*)(A...)) {
return std::tuple<A...>{};
}
template<typename R, typename... A>
constexpr auto parameter_types(std::function<R(A...)>) {
return std::tuple<A...>{};
}
template<typename C, typename R, typename... A>
constexpr auto parameter_types(R(C::*)(A...)) {
return std::tuple<A...>{};
}
template<typename C, typename R, typename... A>
constexpr auto parameter_types(R(C::*)(A...) const) {
return std::tuple<A...>{};
}
}
template<typename F>
using parameter_types = decltype(detail::parameter_types(std::declval<F>()));
template<typename F>
using first_parameter = std::tuple_element_t<0u, parameter_types<F>>;
and now in main you can use first_parameter like this:
int main() {
using R = first_parameter<decltype(accep_float)>;
accep_float(return_r<R>());
}
with this method you can deduce and number of parameters, simple use std::tuple_element_t<N, parameter_types<F>>;
Now it would be neet to make some kind of apply_deduce function that will call the functions accordingly, however you can't just pass a template function name without naming it's template, therefore defeating the purpose.
Not exactly the most elegant, but since there is no other way, a macro will do the job:
#define apply_deduced(f1, f2) f1(f2<first_parameter<decltype(f1)>>())
int main() {
apply_deduced(accep_float, return_r);
}
Basically, what I want to be able to do is take a lambda with any number of any type of parameters and convert it to an std::function.
I've tried the following and neither method works.
std::function([](){});//Complains that std::function is missing template parameters
template <typename T> void foo(function<T> f){}
foo([](){});//Complains that it cannot find a matching candidate
The following code does work however, but it is not what I want because it requires explicitly stating the template parameters which does not work for generic code.
std::function<void()>([](){});
I've been mucking around with functions and templates all evening and I just can't figure this out, so any help would be much appreciated.
As mentioned in a comment, the reason I'm trying to do this is because I'm trying to implement currying in C++ using variadic templates. Unfortunately, this fails horribly when using lambdas. For example, I can pass a standard function using a function pointer.
template <typename R, typename...A>
void foo(R (*f)(A...)) {}
void bar() {}
int main() {
foo(bar);
}
However, I can't figure out how to pass a lambda to such a variadic function. Why I'm interested in converting a generic lambda into an std::function is because I can do the following, but it ends up requiring that I explicitly state the template parameters to std::function which is what I am trying to avoid.
template <typename R, typename...A>
void foo(std::function<R(A...)>) {}
int main() {
foo(std::function<void()>([](){}));
}
You can't pass a lambda function object as an argument of type std::function<T> without explicitly specifying the template argument T. Template type deduction tries to match the type of your lambda function to the std::function<T> which it just can't do in this case - these types are not the same. Template type deduction doesn't consider conversions between types.
It is possible if you can give it some other way to deduce the type. You can do this by wrapping the function argument in an identity type so that it doesn't fail on trying to match the lambda to std::function (because dependent types are just ignored by type deduction) and giving some other arguments.
template <typename T>
struct identity
{
typedef T type;
};
template <typename... T>
void func(typename identity<std::function<void(T...)>>::type f, T... values) {
f(values...);
}
int main() {
func([](int x, int y, int z) { std::cout << (x*y*z) << std::endl; }, 3, 6, 8);
return 0;
}
This is obviously not useful in your situation though because you don't want to pass the values until later.
Since you don't want to specify the template parameters, nor do you want to pass other arguments from which the template parameters can be deduced, the compiler won't be able to deduce the type of your std::function argument.
TL;DR: What you ask can be done using CTAD, a feature that enables you to create an std::function of the expected type, right at the call site without spelling out the template arguments:
foo(std::function([](int arg){ return Bar{}; }));
// ^^^^^^^^^^^^^ constructor call w/o templates
// std::function<Bar(int)> will be auto-deduced
Demo
If you are interested on how to emulate the mechanics of such a deduction, or need to work with a pre c++17 compiler, check the rest of the answer.
You can use a dedicated/retrospective cast. Once you have a tool like this
#include <functional>
using namespace std;
template<typename T>
struct memfun_type
{
using type = void;
};
template<typename Ret, typename Class, typename... Args>
struct memfun_type<Ret(Class::*)(Args...) const>
{
using type = std::function<Ret(Args...)>;
};
template<typename F>
typename memfun_type<decltype(&F::operator())>::type
FFL(F const &func)
{ // Function from lambda !
return func;
}
you can say FFL() to all lambda types to have them converted to what would be the correct version of std::function
template <typename... Args> void Callback(std::function<void(Args...)> f){
// store f and call later
}
int main()
{
Callback(FFL([](int a, float b){
// do something
}));
return 0;
}
Display
As shown at Inferring the call signature of a lambda or arbitrary callable for "make_function", you can infer the calling signature of a lambda (or any other functor with a single calling signature) from its (single) operator():
template<typename T> struct remove_class { };
template<typename C, typename R, typename... A>
struct remove_class<R(C::*)(A...)> { using type = R(A...); };
template<typename C, typename R, typename... A>
struct remove_class<R(C::*)(A...) const> { using type = R(A...); };
template<typename C, typename R, typename... A>
struct remove_class<R(C::*)(A...) volatile> { using type = R(A...); };
template<typename C, typename R, typename... A>
struct remove_class<R(C::*)(A...) const volatile> { using type = R(A...); };
template<typename T>
struct get_signature_impl { using type = typename remove_class<
decltype(&std::remove_reference<T>::type::operator())>::type; };
template<typename R, typename... A>
struct get_signature_impl<R(A...)> { using type = R(A...); };
template<typename R, typename... A>
struct get_signature_impl<R(&)(A...)> { using type = R(A...); };
template<typename R, typename... A>
struct get_signature_impl<R(*)(A...)> { using type = R(A...); };
template<typename T> using get_signature = typename get_signature_impl<T>::type;
This is a rather inflexible approach, though; as R. Martinho Fernandes says, it won't work for functors with multiple operator()s, nor for functors with templated operator() or for (C++14) polymorphic lambdas. This is why bind defers inference of its result type until the eventual call attempt.
It is possible to get the needed std::function type for lambda using derivation, decltype, variadic templates and a few type traits:
namespace ambient {
template <typename Function>
struct function_traits : public function_traits<decltype(&Function::operator())> {};
template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const> {
typedef ReturnType (*pointer)(Args...);
typedef const std::function<ReturnType(Args...)> function;
};
template <typename Function>
typename function_traits<Function>::function to_function (Function& lambda) {
return static_cast<typename function_traits<Function>::function>(lambda);
}
template <class L>
struct overload_lambda : L {
overload_lambda(L l) : L(l) {}
template <typename... T>
void operator()(T&& ... values){
// here you can access the target std::function with
to_function(*(L*)this)(std::forward<T>(values)...);
}
};
template <class L>
overload_lambda<L> lambda(L l){
return overload_lambda<L>(l);
}
}
I use it in my code like this:
ambient::lambda([&](const vector<int>& val){
// some code here //
})(a);
PS: in my real case I then save this std::function object and its arguments inside a generic kernel objects that I can execute later on demand via virtual functions.
Isn't currying already implemented with std::bind?
auto sum = [](int a, int b){ return a+b; };
auto inc = std::bind( sum, _1, 1 );
assert( inc(1)==2 );
This could be interesting for you: https://gist.github.com/Manu343726/94769034179e2c846acc
That is an experiment I have written a month ago. The goal was to create a functor-like C++ template which emulates Haskell's partial calls closures, i.e. the automatic creation of a closure of m-n argumments when you call with n argumments a function with m parameters.
This is one example of what this experiment is cappable to do:
int f( int a, int b, int c, int d)
{
return a+b+c+d;
}
int main()
{
auto foo = haskell::make_function( f );
auto a = foo , 1 , 2 , 3; //a is a closure function object with one parameter
std::cout << a , 4 << std::endl; //Prints 10
}
haskell::make_function uses some type traits to take care of the different types of function entities, lambdas included:
auto f = haskell::make_function( []( int x, int y , int z ){ return x*y*z; } );
auto a = f(1,2); //a is functor with one parameter (Using the alternative C++-like syntax)
auto b = a(3); // b is 6
As you can see, I use comma operator to mmimic Haskell syntax, but you could change it to the call operator to achieve your goal syntax.
Your are completely free to do anything you want with the code (Check the license).
In C++17 there is the constructor type deduction. So you can save some typing for the std::function template arguments. This is not quite nothing, but a bit less.
template <typename R, typename...A>
void foo(std::function<R(A...)>) {}
int main() {
foo(std::function([](){}));
}
Seven years later and probably the simplest solution then, still works today.
template< char const * (*name) () >
struct user {
auto id() { return name(); }
} ;
Usage
constexpr auto lama () { return "Lama"; }
int main( int , char * [] )
{
auto amuser = user< lama >{} ;
cout << boolalpha << amuser.id() << endl ;
}
Lambda afficionados are served too
auto cat = [] () constexpr { return "Cat"; } ;
auto sneaky = user< cat >{} ;
cout << boolalpha << sneaky.id() << endl ;
With lambda expressions that have explicit template parameter lists (C++20 feature), you can write the function much easier as shown below:
template <typename F,typename... T>
auto func(F f, T... values) {
return f(values...);
}
int main() {
auto result = func([]<typename... T>(T...args){
return (...*args);
},1,2,3,6,22);
std::cout<<result<<"\n";
}
with std::result_of, if you use only function (no class/struct, 'cause the declaration would be nothing like the std::function, and it really ugly),you can now make it like:
template <typename Func, typename ...Args>
std::result_of_t<Func(Args...)> func(Func function, Args... args) {
/// now do your staff here
}
/// usage:
func([](){printf("lambda function\n"});
I have a templated function wrapper that I am attempting to update to C++11 syntax (variadic paremeters).
My issue is that I am caught in a "catch 22" where 'Args...' must be the last template parameter, but at the same time, cannot be defined after the function pointer template parameter.
Any idea if this can actually be solved?
template <typename... Args, void(*Function)(Args...)>
class function
{
public:
void operator ()(Args... args) const
{
(*Function)(std::forward<Args...>(args...));
}
};
A possible way is to use the template specialization
template <typename>
struct myFunc;
template <typename R, typename ... Args>
struct myFunc<R(*)(Args...)>
{
// ...
};
but, this way, you intercept (as template parameter) the type of the function pointer, not the function pointer itself; so you have to pass the function pointer in some way (constructor?).
Also observe that, if you want to use perfect forwarding, you have to transform operator() in a template method receiving arguments as universal references (&&).
Something as follows
template <typename ... As>
R operator() (As && ... args) const
{
return fun(std::forward<As>(args)...);
}
where fun is a pointer of type R(*)(Args...).
The following is a full compiling example
#include <iostream>
#include <utility>
int foo (int, long)
{ return 42; }
template <typename>
struct myFunc;
template <typename R, typename ... Args>
struct myFunc<R(*)(Args...)>
{
using funPnt = R(*)(Args...);
funPnt fun = nullptr;
myFunc (funPnt f0) : fun{f0}
{ }
template <typename ... As>
R operator() (As && ... args) const
{
return fun(std::forward<As>(args)...);
}
};
int main ()
{
myFunc<decltype(&foo)> mf0{&foo};
std::cout << mf0(1, 2l) << std::endl;
}
If you really want the pointer function as template parameter (but, this way, every function determine a different type; this can be a good or a bad thing according to your needs), you can write the myFunc struct receiving before a type (the same pointer type) and then a value of that type.
So
template <typename T, T>
struct myFunc;
template <typename R, typename ... Args, R(*Func)(Args...)>
struct myFunc<R(*)(Args...), Func>
{
template <typename ... As>
R operator() (As && ... args) const
{
return Func(std::forward<As>(args)...);
}
};
that can be declared
myFunc<decltype(&foo), foo> mf0;
If you can use C++17, you can simplify using auto for type of template values; so you can avoid the type
template <auto>
struct myFunc;
template <typename R, typename ... Args, R(*Func)(Args...)>
struct myFunc<Func>
{
template <typename ... As>
R operator() (As && ... args) const
{
return Func(std::forward<As>(args)...);
}
};
and you can create a myFunc object as follows
myFunc<&foo> mf0;
Addendum: if you can use C++17, you can define a deduction guide for the first example (pointer as member, not as template value parameter)
template <typename R, typename ... Args>
myFunc (R(*)(Args...)) -> myFunc<R(*)(Args...)>;
so, instead of
myFunc<decltype(&foo)> mf0{&foo};
you can simply write
myFunc mf0{&foo};
Off Topic: I hope that you know that you're reinventing the wheel. As suggested by NathanOliver, the standard provide std::function.
Consider following code
template<typename T>
T modify(const T& item, std::function<T(const T&)> fn)
{
return fn(item);
}
When trying to use it as modify(5, [](const int& i){return 10*i;}); it fails to compile with
could not deduce template argument for 'std::function<T(const T &)> from lambda
I know that compiler can not deduce T from lambda, because lambda is not std::function, but isn't T already deduced from 5?
I can get over it using
template<typename T, typename F>
T modify(const T& item, const F& functor)
{
return functor(item);
}
for which previous example compiles, but it is in my opinion less intuitive. Is there a way to let the function argument to remain std::function and have it's template argument deduced automatically from item?
What you basically want to do is prevent deduction from happening. If template deduction occurs, it will fail (because a lambda is not a std::function<> - it doesn't matter that T was deduced from the first argument, deduction must succeed in every argument that is a deduced context). The way to prevent deduction is to stick the entire argument in a non-deduced context, the easiest way of doing that is to throw the type into a nested-name-specifier. We create such a type wrapper:
template <class T> struct non_deduce { using type = T; };
template <class T> using non_deduce_t = typename non_deduce<T>::type;
And then wrap the type in it:
template<typename T>
void foo(const T& item, std::function<void(T)> f);
template<typename T>
void bar(const T& item, non_deduce_t<std::function<void(T)>> f);
foo(4, [](int ){} ); // error
bar(4, [](int ){} ); // ok, we deduce T from item as int,
// which makes f of type std::function<void(int)>
Note, however, that:
template <typename T, typename F>
void quux(const T&, F );
is not really any less readable, and strictly more performant.
You can do it by using the identity trick as below:
template <typename T>
struct identity {
typedef T type;
};
template<typename T>
T modify(const T& item, typename identity<std::function<T(const T&)>>::type fn) {
return fn(item);
}
Live Demo
I have a template that has a function pointer as it's 2nd parameter and a type that the function pointer is dependent on as it's first.
i.e.
template <typename P, typename void(*fn)(P)>
auto function(P) -> otherType<P, fn>;
I want to make it so that I can just specify the function pointer in the template list without having to specify the dependent type as that type should somehow be able to be inferred from the function pointer that I specify (or maybe even the parameter list, but I think that it probably is too far down the line).
My first thought was to defer the conversion to a template parameter value, by passing a template typename and then convert to a value after the fact though template metaprogramming wizardry.
i.e.
template <typename F, typename P>
auto function(P) -> [[ something here to get otherType<P, fn> if F was a function pointer ]]
However, I'm not sure how I can do this. Any ideas?
Edit
What I'm trying to accomplish here is to make a helper function that will generate a class object. So, given what was said by StenSoft, this is what I've come up with. Unfortunately it doesn't work with a failure inside the main() function where it cannot match to the correct function due to deduction failure:
#include <iostream>
#include <functional>
template<typename T, typename F>
struct wrapper_fntor
{
T m_t;
F m_f;
wrapper_fntor(T t, F f) : m_t(t), m_f(f) {}
void invoke() { m_f(m_t); }
};
template<typename T, void(*fn)(T)>
struct wrapper_fn
{
T m_t;
wrapper_fn(T t) : m_t(t) {}
void invoke() { fn(m_t); }
};
template <typename T>
struct Wrapper;
template <typename Ret, typename P>
struct Wrapper<Ret(P)>
{
template <Ret(*fn)(P)>
static Ret function(P p)
{
return fn(std::forward<P>(p));
}
template <Ret(*fn)(P)>
static P get_param_type(P);
typedef decltype(get_param_type<Ret(P)>()) param_t;
};
template<typename F>
wrapper_fn<typename Wrapper<F>::param_t, &Wrapper<F>::function> make_wrapper(typename Wrapper<F>::param_t param)
{
return wrapper_fn<typename Wrapper<F>::param_t, &Wrapper<F>::function>(param);
}
template<typename F>
wrapper_fntor<typename Wrapper<F>::param_t, F> make_wrapper(typename Wrapper<F>::param_t param, F fntor)
{
return wrapper_fntor<typename Wrapper<F>::param_t, F>(param, fntor);
}
void function(int value)
{
std::cout << "function called " << value << std::endl;
}
int main()
{
auto x = make_wrapper<function>(3);
x.invoke();
}
demo
For a similar problem I have used a templated function inside a templated wrapper class and a macro (this actually works with any parameters and return type):
template <typename T>
struct Wrapper;
template <typename Ret, typename... Params>
struct Wrapper<Ret(Params...)>
{
template <Ret(*fn)(Params...)>
static Ret function(Params... params)
{
return fn(std::forward<Params>(params)...);
}
};
#define FUNCTION(fn) \
Wrapper<decltype(fn)>::function<fn>