我正在尝试开始学习 C++,但遇到了问题。
我正在尝试创建一个函数模板,
template<multimap<string, double> arr>
void calculate(string key) {
}
并像这样使用它:
multimap<string, double> arr;
vector<string> keys;
// ...
for_each(keys.begin(), keys.end(), calculate<arr>);
但我不理解:
Illegal type for non-type parameter, etc
Please, help me. How to arhive the behavior I expect? I really don't want to create a callback for every for_each, etc. (Maybe, closures have made me more lazy than it needed for C++ and I have to, but I don't want to believe)
(btw, is there a way to get a vector with keys from multimap?)
I've tried
typedef multimap<string, double> my_map;
template<my_map arr>
还是不行
最佳答案
我不知道您要做什么,但是模板是按类型参数化的。一个普通的函数或一个函数对象应该做你想做的。
那么让我们让你的函数看起来像这样:
void calculate(const string &key, multimap<string, double>& myMap)
{
// do something...
}
现在我们可以使用 STL 的绑定(bind)器 和ptr_fun
将您的函数转换为对象并将其第二个参数绑定(bind)到您的 map 。
multimap<string, double> map1;
vector<string> v = getValuesForMyVector();
for_each(v.begin(), v.end(), bind2nd(ptr_fun(calculate), map1);
所以发生的事情是ptr_fun(calculate)
转换 calculate
,这是一个指向函数的指针,指向一个名为 pointer_to_binary_function<string, multimap<string, double>, void>
的特殊类其中有 operator()
定义为调用您的函数,即它需要 2 个参数。
bind2nd(ptr_fun(calculate), map1)
返回 binder2nd<string, void>
还有operator()
已定义,但现在它只需要 1 个参数。第二个参数绑定(bind)到 map1。这允许 for_each
使用此函数对象进行操作。
当然,如果您创建一个函数,您将不得不使用这两个适配器。更好的方法是创建一个类:
class MapCalculator
{
public:
MapCalculator(multimap<string, double>& destination) : map_(destination) {}
void operator()(const string& s)
{
// do something...
}
private:
multimap<string, double>& map_;
};
// later...
multimap<string, double> map1;
vector<string> v = getValuesForMyVector();
for_each(v.begin(), v.end(), MapCalculator(map1));
关于c++ - 变量作为 C++ 模板的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1655996/