jav*_*ver 7 c++ templates readability function-pointers c++11
我成功地传递了一个函数作为参数.
// 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
Run Code Online (Sandbox Code Playgroud)
那些Dummy降低了代码的可读性.
我可以用更简洁的方式打电话吗?
AMap<G,int,
[](G&goo)->int{ return goo.doSomething (); }
>map;
Run Code Online (Sandbox Code Playgroud)
我试过,但编译说
expected compile-time constant expression
Run Code Online (Sandbox Code Playgroud)
看起来编译器认为lambda函数不是编译时常量,但我确信它的行为是.
我已阅读如何使用lambda表达式作为模板参数?,但没有解决方案可以提供1语句的方式.
如果我可以称之为,我会是理想的
AMap<G,int, G::doSomething >map; //note that G::doSomething is non-static
Run Code Online (Sandbox Code Playgroud)
编辑
这就是我宣布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
}
Run Code Online (Sandbox Code Playgroud)
您的答案也可以更改上述类的代码.
编辑2:对AMap的任何修改都不算作额外的行,因为它是一个库.
编辑3:对不起,我的模板可能会产生误导.
地图仅使用1个函数进行散列.
template<class K,class T,int (* K_uniqueHash)(K&) >AMap
^key ^value ^ hashing function
Run Code Online (Sandbox Code Playgroud)
因此,我不希望每1键分配1个功能.
换句话说,松散地说....
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"
Run Code Online (Sandbox Code Playgroud)
用一个std::function代替:
AMap<G,int, std::function<int(G&)>> m;
Run Code Online (Sandbox Code Playgroud)
编辑:
您可以AMap按如下方式更改课程:
template<typename K, typename T, typename F>
class AMap {
int getIndex(K& k) { return K_uniqueHash(k); }
// ...
};
Run Code Online (Sandbox Code Playgroud)
假设你有class Foo一个成员函数bar:
struct Foo {
int bar(G&);
};
Run Code Online (Sandbox Code Playgroud)
你可以传递成员函数以及lambdas等:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
239 次 |
| 最近记录: |