模板作为类中的参数

时间:2014-08-18 10:39:23

标签: c++ templates

我有头文件,在我的头文件中我制作了一个模板,我想在一个函数上使用模板,而不是强制所有其他函数。是否有可能像我在main中那样在函数之前获取类型? 这是一个例子:

TestTemp.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

TestTemp.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);
}

有任何想法吗?

4 个答案:

答案 0 :(得分:1)

您的TestTemp已经是模板类,无需进行总和模板功能。

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

答案 1 :(得分:0)

// 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文件并不是一个上帝的想法。对于模板函数,只需将其放在头文件中即可。

答案 2 :(得分:0)

你应该看看here。有很多例子。

我认为如果您删除

,它应该按预期工作
template<class T>

来自

#ifndef _TESTTEMP_H_
#define _TESTTEMP_H_
--> template<class T> <--
class TestTemp  

块。当您只想要一个方法来获取模板参数时,您不必将整个类定义为模板化。

答案 3 :(得分:0)

你只需要将TestTemp定义为正常类,其中&#34; sum&#34;是一个模板功能。然后在你的函数&#34; main&#34; (即调用者),模板参数将从函数参数中推导出来。

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;
}
相关问题