在vector迭代器上调用模板化方法

C++ call templated method on vector iterator

本文关键字:方法 调用 vector 迭代器      更新时间:2023-10-16

我试图访问一个模板化的方法从一个向量迭代器,但我不能编译我的代码,我通过一些错误。

下面是我的代码示例(没有构造函数、析构函数以及所有属性和方法)。然而,这个代码片段再现了我得到的错误。
#include <vector>
#include <boost/any.hpp>
class Value: public boost::any {
public:
  Value () :
      boost::any() {
  }
  template<typename dataT>
  Value (const dataT& value) :
      boost::any(value) {
  }
  template<typename dataT>
  dataT as () const {
    return boost::any_cast<dataT>(*this);
  }
};
class Src {
public:
  inline const Value& operator[] (const int& index) const {
    return _values[index];
  }
  inline Value& operator[] (const int& index) {
    return _values[index];
  }
  template<typename dataT>
  dataT getValue (const int& index) const {
    return operator[](index).as<dataT>();
  }
private:
    std::vector<Value> _values;
};
template<typename SRC>
class A{
public:
  template<typename dataT>
  std::vector<dataT> getValues (const size_t& attr_index) const {
    std::vector<dataT> data;
    typename std::vector<dataT>::iterator src;
    for (src = _data.begin(); src != _data.end(); ++src) {
      data.push_back(src->getValue<dataT>(attr_index));
    }
    return data;
  }
private:
  std::vector<SRC> _data;
};

编译错误如下:

test.h: In member function ‘std::vector<dataT> A<SRC>::getValues(const size_t&) const’:
test.h:49:41: error: expected primary-expression before ‘>’ token
       data.push_back(src->getValue<dataT>(attr_index));

我不知道这里发生了什么。

你知道我做错了什么吗?

编辑:不完全重复如何调用模板成员函数?然而,这里给出的答案https://stackoverflow.com/a/613132/2351966非常有趣,也回答了我的问题,正如Mattia F. as指出的那样,缺少一个template关键字。

在第47行添加关键字template:

data.push_back(src->template getValue<dataT>(attr_index));

否则可以解析为比较操作,如:

(src->getValue < dataT) > (attr_index)