调用类的模板化成员

时间:2015-04-04 14:06:02

标签: c++ class templates

我编写了一个具有模板化成员函数的类,主要是因为它需要std::vector作为参数,但是我很难找到一种正确的方法来调用它。

class foo(){
    // ...
    template <typename _t> int bar(const std::vector<_t> *values);
    // ...
}

稍后用以下方法调用此函数时:

// ...
foo c;
std::vector<int> v(5,100);
c.bar(&v);
// ...

我收到错误:

error: no matching function for call to ‘foo::bar(std::vector<int>*)’
c.bar(&v);

foo::bar(std::vector<int>*)是否应该符合模板参数?为什么不编译?

1 个答案:

答案 0 :(得分:1)

工作示例:

#include <vector>

class foo{
public:
         template <typename _t> int bar(const std::vector<_t> *values) {
            return 1;
         }

};


int main() {
   foo c;
   std::vector<int> v(5,100);
   c.bar(&v);
}

如果你真的需要它不要内联你可以:

//from here
#include <vector>

class foo{
public:
         template <typename _t> int bar(const std::vector<_t> *values);

};

template <typename _t> int foo::bar(const std::vector<_t> *values) {
    return 0;
}
//to here - should be in header file to allow compiler to link it!

int main() {
   foo c;
   std::vector<int> v(5,100);
   c.bar(&v);
}
相关问题