2016-07-05 47 views
0

我試圖從向量迭代器訪問模板化方法,但我無法編譯我的代碼,並且遇到了一些錯誤。向量迭代器上的C++調用模板化方法

這裏是我的代碼示例(沒有構造函數,析構函數和所有屬性和方法)。但是,這段代碼重現了我得到的錯誤。

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

我不知道什麼會發生在這裏的想法。

你知道我在做什麼錯嗎?

編輯:不完全是How to call a template member function?的副本。然而,在這裏給出的答案是https://stackoverflow.com/a/613132/2351966安靜有趣,我的問題也回答爲Mattia F。正如指出的那樣,有一個template關鍵字缺失。

+2

'SRC->模板的getValue (attr_index)'? – Arunmu

+0

感謝它的工作! – Elendil

回答

1

在管線47添加關鍵字template

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

否則會被解析爲一個比較操作,如:

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

謝謝你的工作正常。我不確定要理解爲什麼代碼像'(src-> getValue < dataT) >(attr_index)''沒有關鍵字'模板'一樣被解析。 – Elendil