在不同的文件中实例化模板
Templating template instantiation in different file
我知道以下方法有效:
测试.h
#pragma once
#include <string>
class testclass
{
private:
std::string _data;
public:
template<class T>
testclass(const T&);
};
测试.cpp
#include "test.h"
template testclass::testclass(const int&);
template testclass::testclass(const long&);
//function can be called only with `int` and `long`
template<class T>
testclass::testclass(const T &num)
: _data(std::to_string(num))
{}
因此,这是拆分模板函数的声明和实现的一种成功方法,但也有一些缺点。其中之一是必须对所有类型进行硬编码,您希望用这些类型来调用函数,这是一种拖累。如果这个函数很小,那么你最终编写的代码比你没有模板化的时候要多…
我想知道这样的事情是否可能:
测试.cpp
#include "test.h"
template<class T2> //bogus syntax, but here the point of interest
template testclass::testclass(const T2&);
template<class T>
testclass::testclass(const T &num)
: _data(std::to_string(num))
{}
我想知道这样的事情是否可能:
不,那是不可能的。
您的选择是:
-
让
testclass
的每个用户都包含定义。 -
在一个包含定义的编译单元中定义
testclass::testclass
的每个所需实例。
没有其他选择。
为什么不在.h
中直接在类上使用模板?
#pragma once
#include <string>
template <T>
class testclass
{
private:
std::string _data;
public:
testclass(const T& num) : data(std::to_string(num)) {}
};
这样,你就可以将你的类与你想要的任何类型一起使用,例如:
testclass<int> test(1);
testclass<double> test(2.0);
...
我认为这是不可能的,因为在编译阶段,编译器只能看到test.cpp文件,而不知道它必须实例化该模板的哪些类型。
因此,如果您只想为了模块化目的而将模板拆分为h/cpp文件,您可以尝试以下技巧:
- 将"test.cpp"文件重命名为"test.tpp"(*.tpp扩展名只是显示它是此处的模板类定义)
- 保持*.h文件不变,但在末尾添加#include"test.tpp"语句
可能您必须将includes从*.tpp移到test.h的头上,但我不确定,只需使用它即可。
相关文章:
- OSX clang++:用于 cpp 文件中显式实例化模板的体系结构x86_64的未定义符号
- 将类成员函数的模板定义放在 CPP 文件中C++隐式实例化而不是 .H 允许吗?
- 即使我正在.cpp文件中实例化一个伪对象,.cpp文件内模板函数的定义也不起作用
- 如何使用 c++ 从另一个 cpp 文件中的 main.cpp 调用实例化类
- 如何在C++实现文件中实例化类?
- 模板类静态在最终二进制文件中跨共享库以不同方式实例化是否一致
- 从文件实例化:构造函数采用std:ifstream&作为参数
- 如何将模板定义和实例化分为HPP和IPP文件
- 在头文件中包含std::vector会导致模板实例化错误
- C++ 类文件中的对象实例化
- 模板函数实例化文件
- C++ 无法实例化编解码器以在 txt 文件中写入 unicode
- 从文件描述符实例化套接字对象的非侵入性方法
- 对在头文件中实例化指针感到困惑
- 如何根据对象文件中缺少的符号实例化模板
- 头文件中的模板实例化
- C++ 使用单个输入字节文件的不同部分实例化堆栈上的成员类
- 是否有任何方法可以避免cpp文件中所有方法的重复类实例化
- 如何重定向头文件(到库)以在实例化中包含一些代码
- 使用头文件实例化和使用 c++ 类