C++模板函数声明与定义分开
1.头文件声明
//file name: T_template.h
#pragma once
#include <iostream>
#include <string>
using namespace std;
template<class T1, class T2>
class T_flower
{
public:
T_flower(T1 tName,T2 tAge);
~T_flower();
void Show(void);
public:
T1 mName;
T2 mAge;
};
2.类的定义
//file name: T_template.hpp
#include "T_template.h"
template<class T1, class T2>
T_flower<T1,T2>::T_flower(T1 tName,T2 tAge)
{
this->mName = tName;
this->mAge = tAge;
}
template<class T1, class T2>
T_flower<T1,T2>::~T_flower(){}
template<class T1, class T2>
void T_flower<T1,T2>::Show(void)
{
cout << "name: " << this->mName << endl;
cout << "age: " << this->mAge<<endl;
}
3.调用
//file name: main.cpp
#include "swap.h"
#include "T_template.h"
#include "T_template.hpp"
void test6(void);
int main(int argc, char **argv)
{
test6();
return 0;
}
void test6(void)
{
T_flower<string ,int> rose("jili",2);
rose.Show();
}
4.CMakeLists.txt编写
cmake_minimum_required(VERSION 3.0.0)
project(cmake_project VERSION 0.1.0)
include(CTest)
enable_testing()
set(CMAKE_CXX_STANDARD 11)
include_directories(
./include
./hpp
)
aux_source_directory(./src DIR_SRCS)
aux_source_directory(./hpp DIR_SRCS)
add_executable(cmake_main main.cpp ${DIR_SRCS})
set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)