65,179
社区成员




template < typename T1,typename T2 >
class CMyClass
{
template<typename _Ty>
void diff(_Ty & t);
void diff(std::string & t);
public:
void func();//调用diff,当T2为string时调用的函数为void diff(std::string & t);
};
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
template<typename T3, typename T4>
struct must_be_same_type
{
enum { ret = 0 };
};
template<>
struct must_be_same_type<string, string>
{
enum { ret = 1 };
};
template < typename T1,typename T2 >
class CMyClass{
public:
void myfun(){
if(must_be_same_type<T2, string>::ret){
cout<<"很黄,很暴力"<<endl;
}else{
cout<<"很傻,很天真"<<endl;
}
}
};
int main(int argc, char *argv[])
{
CMyClass<int, int> a;
a.myfun();
CMyClass<int, string> b;
b.myfun();
system("PAUSE");
return 0;
}
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
template<typename T>
void fun(){}
template<>void fun<string>(){
cout<<"hello,wrod"<<endl;
}
template < typename T1,typename T2 >
class CMyClass{
public:
void myfun(){
//.....template模式
fun<T2>();
//.....template模式
};
int main(int argc, char *argv[])
{
CMyClass<int, string> aa;
aa.myfun();
system("PAUSE");
return 0;
}
#include<iostream>
#include<string>
using namespace std;
template<class T>
void f(T) {
cout << "in template version" << endl;
}
void f(string) {
cout << "in string version" << endl;
}
int main() {
string test;
f(test);
f<string>(test);
cin.get();
}
#include <iostream>
#include <string>
using namespace std;
template <typename T>
void foo( const T& v )
{
cout << "logic2 simple: " << v << endl;
}
void foo( const string& v )
{
cout << "logic2 string: " << v << endl;
}
template <typename T1, typename T2>
class bar
{
public:
bar( const T1& v1, const T2& v2 ) : _t1(v1), _t2(v2)
{
func();
}
void func()
{
cout << "logic1: " << _t1 << endl;
foo<T2>( _t2 );
}
T1 _t1;
T2 _t2;
};
void main()
{
bar<int, float> c1(1, 10.0);
bar<float, float> c2(2.0, 20.0);
bar<float, string> c3(3.0, string("hello, world"));
}
#include <cstdlib>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
template < typename T1,typename T2 >
class CMyClass{
public:
void myfun(){
if( typeid(std::string) == typeid(T2))
{
cout<<"很黄,很暴力"<<endl;
}else{
cout<<"很傻,很天真"<<endl;
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
CMyClass<int, string> a;
a.myfun();
CMyClass<int, int> b;
b.myfun();
return 0;
}
template <typename T1,typename T2>
class CMyClass
{
template <typename T>
void fun(){}
template <>
void fun<string>(){}
};
函数好象不支持偏特话,所以你还是特化吧
template<typename t1, typename t2>
struct test {
};
template<typename t1>
struct test<t1, string> {
};
//无敌子类
template < typename T1,typename T2 >
class CMyClass
{virtual void func();}
template< typename T >
class CMyClass_string : public CMyClass<T, std::string>
{virtual void func();}