c++ - 变量作为 C++ 模板的参数

标签 c++ templates stl

我正在尝试开始学习 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/

相关文章:

c++ - 使用 twinview Ubuntu 12.04 c++ 在 2 个显示器上的全屏应用程序

c++ - const 和非常量迭代器的一个类。是否可以?

C++ 排序和跟踪索引

c++ - 检测类型是否为 std::tuple?

c++ - 为什么在这种情况下非类型模板参数不能是自动的?

javascript - 社交媒体按钮不会出现在 BlogSpot 上

STL - 我可以在 DriverKit 驱动程序中使用 STL 吗?

c++ - 对派生对象的 C++ 虚函数调用是否通过 vtable?

c++ - 奇怪的 GCC 数组初始化行为

c++ - 以编程方式在 C++ 中获取 "Operating System Context"