c++ - Template as parameter in class -


i have header file , in header file make template , want use template on 1 function , not force other functions. possible type before function did in main? example:

testtemp.h

// testtemp.h #ifndef _testtemp_h_ #define _testtemp_h_ template<class t> class testtemp   { public:     testtemp();     void setvalue( int obj_i );     int getalue();     void sum(t b, t a);  private:     int m_obj; }; #include "testtemp.cpp"  #endif 

testtemp.cpp

//testtemp.cpp include<testtemp.h> testtemp::testtemp() { } void testtemp::setvalue( int obj_i ) {     m_obj = obj_i ; }  int testtemp::getvalue() {     return m_obj ; }  template<class t> void testtemp<t>::sum(t b, t a) {     t c;     c = b + a; } 

main.cpp

//main.cpp include<testtemp.h> void main() {     testtemp t;     t.sum<int>(3,4); } 

have ideas?

your testtemp template class already, no need make sum template function.

testtemp<int> t; t.sum(3, 4); 

if want make sum function template function of testtemp:

template<class t> class testtemp   { public:     //....     template<typename u>     void sum(u b, u a);  private:     int m_obj; }; 

to implement outside template class:

template<class t> template<typename u> void testtemp<t>::sum(u b, u a) {     t c;     c = b + a; }  int main() {     testtemp<int> t;     t.sum<int>(3, 4); } 

however, feel need free template function

template<typename t> t sum(t a, t b) { return + b; } 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -