大佬教程收集整理的这篇文章主要介绍了c – 在1个语句中将自定义函数作为模板参数传递,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
// 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
那些Dummy降低了代码的可读性.
我可以用更简洁的方式打电话吗?
AMap<G,[](G&goo)->int{ return goo.doSomething (); } >map;
我试过,但编译说
expected compile-time constant expression
看起来编译器认为lambda函数不是编译时常量,但我确信它的行为是.
我已阅读How to use a lambda expression as a template parameter?,但没有解决方案可以提供1语句方式.
如果我可以称之为,我会是理想的
AMap<G,G::doSomething >map; //note that G::doSomething is non-static
编辑
这就是我宣布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 }
您的答案也可以更改上述课程的代码.
编辑2:对AMap的任何修改都不算作额外的行,因为它是一个库.
编辑3:对不起,我的模板可能会产生误导.
template<class K,int (* K_uniqueHash)(K&) >AMap ^key ^value ^ hashing function
换句话说,松散地说….
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"
AMap<G,std::function<int(G&)>> m;
编辑:
您可以按如下方式更改AMap类:
template<typename K,typename T,typename F> class AMap { int geTindex(K& k) { return K_uniqueHash(k); } // ... };
struct Foo { int bar(G&); };
你可以传递成员函数以及lambdas等:
AMap<G,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);
以上是大佬教程为你收集整理的c – 在1个语句中将自定义函数作为模板参数传递全部内容,希望文章能够帮你解决c – 在1个语句中将自定义函数作为模板参数传递所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。