我有头文件,在我的头文件中我制作了一个模板,我想只在一个函数上使用该模板,而不是强制所有其他函数。是否可以像我在 main
中那样在函数之前获取类型?
这是一个例子:
测试温度.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
测试温度.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);
}
有什么想法吗?
最佳答案
你的TestTemp已经是模板类了,不用再做sum模板函数了。
TestTemp<int> t;
t.sum(3, 4);
如果你真的想让sum
函数成为TestTemp
的模板函数:
template<class T>
class TestTemp
{
public:
//....
template<typename U>
void sum(U b, U a);
private:
int m_Obj;
};
在模板类之外实现它:
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);
}
不过,我觉得你只需要一个免费的模板功能
template<typename T>
T sum(T a, T b)
{ return a + b; }
关于c++ - 模板作为类中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25361364/