c – 在1个语句中将自定义函数作为模板参数传递

前端之家收集整理的这篇文章主要介绍了c – 在1个语句中将自定义函数作为模板参数传递前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我成功地传递了一个函数作为参数.
  1. // this is in a scope of a normal function
  2. class DummyClass{
  3. public: static int dummyFunction(G& goo){
  4. return goo.doSomething (); //non-static function
  5. //Edit 3: it calculates hash value
  6. }
  7. };
  8. AMap<G,int,DummyClass::dummyFunction>map;
  9. //... do some other thing

那些Dummy降低了代码的可读性.

我可以用更简洁的方式打电话吗?

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

我试过,但编译说

  1. expected compile-time constant expression

看起来编译器认为lambda函数不是编译时常量,但我确信它的行为是.

我已阅读How to use a lambda expression as a template parameter?,但没有解决方案可以提供1语句方式.

如果我可以称之为,我会是理想的

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

编辑

这就是我宣布AMap的方式

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

您的答案也可以更改上述课程的代码.

编辑2:对AMap的任何修改都不算作额外的行,因为它是一个库.

编辑3:对不起,我的模板可能会产生误导.

地图仅使用1个函数进行散列.

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

因此,我不希望每1键分配1个功能.

换句话说,松散地说….

  1. AMap<K,T,k_hasher> aMap;
  2. K k1,k2; T t1,t2;
  3. aMap[ k1 ] = t1; aMap[ k2 ] =t2;
  4. // Then,these statements below will be called internally.
  5. k1.k_hasher();
  6. k2.k_hasher(); //every k call same function "k_hasher"

解决方法

使用std :: function代替:
  1. AMap<G,std::function<int(G&)>> m;

编辑:

您可以按如下方式更改AMap类:

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

假设你有一个带有成员函数栏的Foo类:

  1. struct Foo {
  2. int bar(G&);
  3. };

你可以传递成员函数以及lambdas等:

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

猜你在找的C&C++相关文章