当我需要定义许多类似的方法时,我的目的是避免使用宏样式。所以我很感兴趣,我可以使用模板或类似的东西吗?
这是伪c ++中的一般概念:
template <class T, class U> void myMethod(T t, U u){ ..do a lot .. }
class A {
public:
A(){}
void myMethod<int, int>;
void myMethod<float, char>;
// ... etc
};
答案 0 :(得分:2)
template <class T, class U> class A
{
public:
void MemberSet( T t, U u );
};
增加:
#include <typeinfo>
#include <iostream>
using namespace std;
class A
{
public:
template <class T, class U> void MemberSet( T t, U u ) {
cout << typeid(t).name() << " " << typeid(u).name() << endl;
};
};
int main()
{
A a;
a.MemberSet(5,5);
a.MemberSet<char, long>(5,5);
}
您可能希望显式实例化
template void A::MemberSet<int, long> (int, long);
答案 1 :(得分:2)
不,但您可以使用继承。
template <class derived_T, class T, class U>
struct base {
void myMethod_(T t, U u) {
// use this to access derived class members:
static_cast<derived_T*>(this)->
}
};
struct a : base<a, int, int>, base<a, float, float> {
template <class T, class U>
void myMethod(T&& t, U&& u) {
base<a,T,U>::myMethod_(std::forward<T>(t), std::forward<U>(u));
}
};
答案 2 :(得分:1)
不,但你可以:
template <class T, class U> void struct myMethodWrapper
{
void myMethod(T t, U u){ ..do a lot .. }
};
然后:
class A : public myMethodWrapper<int, int>,
public myMethodWrapper<float, float>
{
};
表现相似。
答案 3 :(得分:1)
另一种选择是将模板代码放在类之外,并从类方法中调用它。
#include <iostream>
using namespace std;
namespace myTemplates
{
// template method 'mult(a,b)'
// returns a*b
template <class T1, class T2>
T1 mult(T1 a, T2 b)
{
T1 result = a * b;
return result;
}
// template specialization 'mult(string aString, int m)'
// returns a string repeated m times
template <>
string mult<string, int>(string input, int m)
{
string result;
for (int i = 0; i < m; i++)
{
result += input;
}
return result;
}
}
class A {
public:
A(){}
int mult(int a , int b ) { return myTemplates::mult(a, b ) ; }
float mult(float a , float b ) { return myTemplates::mult(a, b ) ; }
string mult(string a , int b ) { return myTemplates::mult(a, b ) ; }
};
int main(void)
{
int iA = 2;
int iB = 3;
int iC = 0; // result
float fA = 20.1;
float fB = 30.3;
float fC = 0.0; // result
string sA = " -blah- ";
string sC; // result
iC = myTemplates::mult(iA,iB);
cout << "mult(" << iA << ", " << iB << ") = " << iC << endl;
fC = myTemplates::mult(fA,fB);
cout << "mult(" << fA << ", " << fB << ") = " << fC << endl;
sC = myTemplates::mult(sA,iB);
cout << "mult(" << sA << ", " << iB << ") = " << sC << endl;
A a;
iC = a.mult(iA,iB);
cout << "a.mult(" << iA << ", " << iB << ") = " << iC << endl;
fC = a.mult(fA,fB);
cout << "a.mult(" << fA << ", " << fB << ") = " << fC << endl;
sC = a.mult(sA,iB);
cout << "a.mult(" << sA << ", " << iB << ") = " << sC << endl;
return 1;
}
输出:
mult(2, 3) = 6
mult(20.1, 30.3) = 609.03
mult( -blah- , 3) = -blah- -blah- -blah-
a.mult(2, 3) = 6
a.mult(20.1, 30.3) = 609.03
a.mult( -blah- , 3) = -blah- -blah- -blah-