文件目录
.
├── CMakeLists.txt
├── include
│ └── Operation.h
├── main.cc
└── src
├── CMakeLists.txt
└── Operation.cc
./CMakeLists.txt
cmake_minimum_required(VERSION 3.14)
project(name)
include_directories(include)
add_subdirectory(src)
add_executable(main main.cc)
target_link_libraries(main op)
./include/Operation.h
#pragma once
class Operator{
public:
int m_a;
template<typename T>
T math(T a);
};
./src/Operation.cc
#include "Operation.h"
#include <iostream>
using namespace std;
template<typename T>
T Operator::math(T a){
return a+2;
};
template int Operator::math(int); // 不加这一行将提示:main.cc:(.text+0x36): undefined reference to `int Operator::math<int>(int)'
./main.cc
#inclu

这篇博客详细介绍了如何使用C++的模板特性和CMake构建工具来组织和编译项目。通过一个简单的例子展示了`Operator`类的模板方法`math`,并解释了在`src/Operation.cc`中为何需要显式实例化模板以解决链接错误。此外,还给出了`CMakeLists.txt`文件的内容,说明了如何配置CMake来编译和链接目标文件。
最低0.47元/天 解锁文章
15万+






