2012-10-14 25 views
0

使用 C++中的.h

而t是template<typename T>

string myFunction(T t) { 
    string str1; 
    //some computation with t 
    return str1(); 
} 

所以在我.h文件,我像做

class myClass { 
    private: 
    //some variable 
    public: 
    string myFunction(T); 
} 

和當然它會給出一個錯誤,說「什麼是T?」

我該怎麼辦才能讓myFunction能夠拿到T

回答

3

使一個成員函數模板:

class Foo { 
    template<typename T> 
    string myFunction(T t) 
    { 
    } 
}; 

,或者做一個類模板:

template<typename T> 
class Foo { 
    string myFunction(T t) 
    { 
    } 
}; 

無論是有道理的,你的情況。如果你定義的函數類外,則:

class Foo { 
    template<typename T> 
    string myFunction(T); 
}; 

template<typename T> 
string Foo::myFunction(T t) 
{ 
} 

成員函數模板,或

template<typename T> 
class Foo { 
    string myFunction(T); 
}; 

template<typename T> 
string Foo<T>::myFunction(T t) 
{ 
} 

類模板。