获取模板错误

时间:2015-06-19 13:59:24

标签: c++ templates

我收到编译错误,请帮助我无法解决它

 class A {
        public :
        A() {} 
        virtual ~A() {}

        int getID() { return m_id; }
        void setID(int id) { m_id = id ; }

        private:
        int m_id ;
    };    


    class B : public A {

    };


    class C: public A {

    };

    template<class T>
    T* returnObject(vector<T*>& vec, int id)
    {
        for(vector<T*>::iterator itr =vec.begin();  itr != vec.end() ; ++itr)
        {
            if(id == (*itr)->getID()) return (*itr);
        }
        return NULL;
    }

    int main() 
    {
        vector<B*> b1;
        vector<C*> c1;

        B *b = new B();
        b->setID(10);
        b1.push_back(b);
        b = new B();
        b->setID(20);
        b1.push_back(b);
        b = new B();
        b->setID(30);
        b1.push_back(b);

        C *c = new C();
        c->setID(6);
        c1.push_back(c);
        c = new C();
        c->setID(12);
        c1.push_back(c);
        c = new C();
        c->setID(18);
        c1.push_back(c);

        B *bcd = returnObject<B>(b1,30);

        cout<< bcd <<endl ;

        return 0;
    }

我收到编译错误

castEx.cpp: In function `T* returnObject(std::vector<T*, std::allocator<T*> >&, int)':
castEx.cpp:29: error: expected `;' before "itr"
castEx.cpp:29: error: `itr' was not declared in this scope
castEx.cpp: In function `T* returnObject(std::vector<T*, std::allocator<T*> >&, int) [with T = B]':
castEx.cpp:61:   instantiated from here
castEx.cpp:29: error: dependent-name ` std::vector<T*,std::allocator<T*> >::iterator' is parsed as a non-type, but instantiation yields a type

1 个答案:

答案 0 :(得分:2)

问题是vector<T*>::iterator取决于模板参数。编译器不知道每个std::vector特化都有一个类型的iterator成员,所以你需要明确声明一个类型:< / p>

for(typename vector<T*>::iterator itr =vec.begin();  itr != vec.end() ; ++itr)
//  ^^^^^^^^

有关typename

的详情,请参阅this question

当然,您可以回避C ++ 11中的整个问题,只需使用auto:

for(auto itr =vec.begin();  itr != vec.end() ; ++itr)

或基于范围的for循环:

for (auto&& element : vec)

std::find_if

std::find_if(std::begin(vec), std::end(vec), 
            [id](auto&& el){ return id == el->getID() });

如果找不到元素,std::find_if会返回std::end(vec),而不是NULL