模板作为类中的参数
Template as parameter in class
本文关键字:参数 更新时间:2023-10-16
我有头文件,在我的头文件中我做了一个模板,我想只在一个函数上使用该模板,而不是强制所有其他函数。 是否可以像我在函数中所做的那样在函数之前获取类型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;
}
主.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; }
// TestTemp.h
#ifndef _TEST_TEMP_H_
#define _TEST_TEMP_H_
class TestTemp
{
public:
TestTemp();
void SetValue( int obj_i );
int Getalue();
template<class T>
void sum(T b, T a);
private:
int m_Obj;
};
TestTemp::TestTemp() {}
void TestTemp::SetValue( int obj_i )
{
m_Obj = obj_i ;
}
int TestTemp::Getalue()
{
return m_Obj ;
}
template<class T>
void TestTemp::sum(T b, T a)
{
T c;
c = b + a;
}
#endif
//main.cpp
#include <TestTemp.h>
int main()
{
TestTemp t;
t.sum<int>(3,4);
return 0;
}
你需要的是一个具有模板成员函数的普通类。
在头文件中包含 cpp 文件并不是一个上帝的想法。对于模板函数,只需将其放在头文件中即可。
你应该看看这里。这样的例子很多。
我认为如果您只是删除它,它应该可以按您的预期工作
template<class T>
从
#ifndef _TESTTEMP_H_
#define _TESTTEMP_H_
--> template<class T> <--
class TestTemp
块。当您只希望方法具有模板参数时,不必将整个类定义为模板化。
你只需要将TestTemp定义为普通类,其中"sum"是一个模板函数。然后在你的函数"main"(即调用者(中,模板参数将从函数参数中推导出来。
class TestTemp
{
public:
TestTemp();
void SetValue(int obj_i);
int Getalue();
template<class T>
void sum(T b, T a);
private:
int m_Obj;
};
TestTemp::TestTemp() {}
void TestTemp::SetValue(int obj_i)
{
m_Obj = obj_i;
}
int TestTemp::Getalue()
{
return m_Obj;
}
template<class T>
void TestTemp::sum(T b, T a)
{
T c;
c = b + a;
}
//main.cpp
int main()
{
TestTemp t;
t.sum(3, 4);
return 0;
}
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- 使用指向成员的指针将成员函数作为参数传递
- 没有名称的C++模板参数
- 如何将enable-if与模板参数和参数包一起使用