c++ - 在 1 条语句中将自定义函数作为模板参数传递

标签 c++ templates c++11 function-pointers readability

我成功传递了一个函数作为参数。

// 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,int,
    [](G&goo)->int{ return goo.doSomething (); }
>map;

我试过了,但是编译器说

expected compile-time constant expression

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

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

如果能这样称呼我就完美了

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

编辑

这就是我声明高德 map 的方式

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:抱歉,我的模板可能会产生误导。

一张 map 只使用 1 个函数进行散列。

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

因此,我不希望为每个键分配 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"

最佳答案

改用std::function:

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

编辑:

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

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

假设你有一个class Foo 和一个成员函数bar:

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

您可以传递成员函数以及 lambda 等:

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);

关于c++ - 在 1 条语句中将自定义函数作为模板参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37673919/

相关文章:

c++ - 控制台崩溃,无法识别错误?

c++ - GCC 使用旧版本的 C++

c++ - 尝试使用可变参数编译代码时出错

python - 如何从 Cython 中的 <algorithm> 外部

c++ - 使用 constexpr 函数作为模板参数是否有效?

c++ - 序列容器-只能顺序访问元素

c++ - 开源 Visual Studio 项目分发噩梦

c++ - 如何在 C++ 项目中包含具有相似名称的头文件

c++ - 检查类是否是模板专用化(使用 bool 或 int 等模板参数)

c++ - 对于具有附加(非推导)模板参数的函数,ADL 失败(或未完成?)