Passing a user-defined function as a template parameter in 1 expression

I successfully passed the function as a parameter.

// this is in a scope of a normal function class DummyClass{ public: static int dummyFunction(G& goo){ return goo.doSomething (); //non-static function //Edit 3: it calculates hash value } }; AMap<G,int,DummyClass::dummyFunction>map; //... do some other thing 

These Dummy reduce code readability.

Can this be called a more concise way?

 AMap<G,int, [](G&goo)->int{ return goo.doSomething (); } >map; 

I tried, but the compiler said

 expected compile-time constant expression 

It looks like the compiler thought that the lambda function is not a compile-time constant, but I'm sure its behavior.

I read How to use a lambda expression as a template parameter? , but no solution can suggest a 1-expression.

I would be perfect if I could call him like

 AMap<G,int, G::doSomething >map; //note that G::doSomething is non-static 

Edit

This is how I announced AMap

 template<class K,class T,int (* K_uniqueHash)(K&) >AMap {//<--- can be changed private: int getIndex(K& k){ return K_uniqueHash(k); //<--- can be changed } //.. other function } 

Your answer may also change the codes of the above class.

Edit 2: Any modification to AMap is not considered extra lines, because it is a library.

Edit 3: Sorry, my template may be misleading.

The map uses only 1 hash function.

 template<class K,class T,int (* K_uniqueHash)(K&) >AMap ^key ^value ^ hashing function 

Therefore, I do not expect to assign 1 function to 1 key.

In other words, fluent ....

 AMap<K,T,k_hasher> aMap; K k1,k2; T t1,t2; aMap[ k1 ] = t1; aMap[ k2 ] =t2; // Then, these statements below will be called internally. k1.k_hasher(); k2.k_hasher(); //every k call same function "k_hasher" 
+7
c ++ c ++ 11 templates readability function-pointers
source share
1 answer

Use std::function instead:

 AMap<G,int, std::function<int(G&)>> m; 

Edit:

You can change your AMap class as follows:

 template<typename K, typename T, typename F> class AMap { int getIndex(K& k) { return K_uniqueHash(k); } // ... }; 

Suppose you have a class Foo with a member function bar :

 struct Foo { int bar(G&); }; 

You can pass member functions as well as lambdas, etc. as:

 AMap<G,int, std::function<int(G&)>> m; auto f = [](G &i)->int { return 42; }; m[0] = f; // if your class works like a map Foo foo; m[2] = std::bind(&Foo::bar, &foo, std::placeholders::_1); 
+5
source share

All Articles