模板作为类中的参数

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;
}