c++ - Generic functions taking generic functions as arguments -


i can't find nice way define generic higher-order functions taking generic functions arguments. example, take attempt @ 1 of simplest such functions out there:

template<typename f, typename a> auto apply(f f, const a& a) -> decltype(f(a)){return f(a);} 

of course works intended when used non-template functions. if have, instance

template<typename a> id(const a& a){return a;} 

then

int = 10; int b = apply(id, a); 

will not work, since id expects template parameter. write id<int> make work, sort of defeats purpose (as see it, implies if wanted write "filter" i'd have write separate definition each generic predicate function). using std::function or function pointers did not help. also, tried make "template template" version of apply, various compiler errors when try use it:

template<template<typename> class f, typename a> auto apply2(f<a> f, const a& a)-> decltype(f(a)){return f(a);} 

the best came following:

struct id{     template<typename a>     static func(const a& a){return a;} };  template<typename f, typename a> auto apply(a a)-> decltype(f::func(a)){return f::func(a);} 

it's bit ugly, @ least can parameterize function.

so, there better way generic functions taking generic functions arguments?

this 'functor' works first version of apply.

struct id {     template<typename a>     operator ()(const a& a) {return a;} }; 

later

int b = apply(id(), a); // parenthesis construct struct. 

Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -