Template-Funktion compiliert nicht [gelöst]



  • Hallo,
    ich habe eine Template-Funktion. Visual Studio compiliert sie einwandfrei. Leider jedoch nicht gcc 4.1.2.

    Die Funktion:

    template <class T> inline bool contains(std::vector<T>* in_vct, T in_lv)
    {
    	std::vector<T>::iterator i;
    
    	for (i=in_vct->begin(); i!=in_vct->end(); i++)
    	{
    		if ((*i)==in_lv)
    			return true;
    	}
    
    	return false;
    }
    

    Der Fehler, welcher kommt:

    LatticeVector.h: In function 'bool contains(std::vector<T, std::allocator<_CharT> >*, T)':
    LatticeVector.h:237: error: expected `;' before 'i'
    LatticeVector.h:239: error: 'i' was not declared in this scope
    make: *** [LatticeVector.o] Fehler 1

    Ach ja: <vector> habe ich selbstverständlich included und die Template-Funktion befindet sich in einer Header-Datei 😉



  • typename std::vector<T>::iterator i;



  • Besser:

    template <typename T>
    contains(std::vector<T> const& vs, T const& v) {
        return find(vs.begin(), vs.end(), v) != vs.end();
    }
    

    Oder allgemeiner:

    template <typename T, typename IterT>
    contains(IterT begin, IterT end, T const& v) {
        return find(begin, end, v) != end;
    }
    


  • Danke an beide.


  • Mod

    wolfgke schrieb:

    Hallo,
    ich habe eine Template-Funktion.

    Was du zeigst, ist allerdings ein Funktionstemplate.



  • Konrad Rudolph schrieb:

    Besser:

    template <typename T>
    contains(std::vector<T> const& vs, T const& v) {
        return find(vs.begin(), vs.end(), v) != vs.end();
    }
    

    Oder allgemeiner:

    template <typename T, typename IterT>
    contains(IterT begin, IterT end, T const& v) {
        return find(begin, end, v) != end;
    }
    

    Hmmm, Funktionen mit Rückgabetypen finde ich schöner .... 😉

    Gruß,

    Simon2.


Anmelden zum Antworten