c++ - 如何在头文件和源文件中组织模板函数和函数

标签 c++ function code-organization function-templates

我正在学习使用模板函数并在多个文件中组织我的代码。我看了Why can templates only be implemented in the header file?他们指出我应该在标题中实现我的模板功能;我也看了C++ inline functions: declare as such, define as such, or both? Why?所以我知道我应该在标题中将完全专用的函数定义为内联;我看了看Why use a “tpp” file when implementing templated functions and classes defined in a header?他们建议在单独的 my.tpp 中定义模板(以及完全专用的模板?)并在我的末尾添加 #include "my.tpp" header 。

作为一个完全的初学者,现在我的问题是:如何将所有这些与常规函数结合起来。

想象一下:

#ifndef IVAL_H
#define IVAL_H

//Function to determine if input string is of a given type
template<typename T>
bool is_type(std::string);

//Specialization when testing integer
//As I also want to accept  e.g. 4.0000 as an integer
template<>
bool is_type<int>(std::string);

//Function to get a given type
template<typename T>
T get_type(std::string);

//Finally a normal function to ask for [y/n]
bool yesNo(std::string prompt);

//Include templates definitions
#include"ival.tpp"

#endif /*IVAL_H*/

然后我按照上面引用的问题中的建议:

//in ival.tpp
#ifndef IVAL_TPP
#define IVAL_TPP

template<typename T>
bool is_type(std::string input)
{
//How to validate input
}

template<>
bool inline is_type<int>(std::string input)
{
\\How to validate when integer
}

template<typename T>
T get_type(std::string prompt)
{
//How to keep asking until valid input
//Using is_type
}
#endif /*IVAL_H*/

最后作为 .cpp 我的正常功能:

//in ival.cpp
#include "ival.h"

bool yesNo(std::string prompt)
{
//How to ask for [y/n]
//Using get_type<char>
}

这导致了一些关于如何组织我的函数的正确方法的混淆。当在 header 中我们同时具有模板函数和普通函数时,做我上面做的事情是正常的吗? (普通函数的不同源文件),是将完全专用的函数视为模板(即在所有模板所在的文件中内联定义)还是函数(即仅在 .cpp 中定义为所有其他函数)。

我在 .cpp 中定义模板函数并显式实例化为 char、int、double、floatstd::string 是否更方便? p>

最佳答案

我觉得你的解决方案不错。您通常可以在文件 ival.h 的末尾插入文件 ival.tpp 的代码,因此只有一个头文件。

How do I combine all this with regular functions.

通常的规则是:

  • 只将常规函数的定义放入 *.cpp 文件。
  • 将所有模板函数定义、内联函数定义和常规函数声明放入*.h 文件(或有人喜欢将其称为*.hpp)。选择一个顺序,使大多数函数只使用/调用在它们上面定义的函数。
  • 仅在必要时(例如循环依赖):将足够的模板和内联函数声明放在*.h文件的最顶部,以便所有被调用的函数都是在调用之前声明。这通常只在特殊情况下才有必要。

When in a header we have both template functions and normal functions, is the normal thing to do what I did above?

通常没有必要在定义模板函数之前显式声明它们,因此这通常被省略。这通常只在少数必要的情况下才这样做,即当模板函数相互引用/调用时。调用图中甚至可以有循环。只需将其全部声明为内联并将其实际内联的内容留给编译器。

are the fully specialized functions treated as a template or as a function?

将它们视为模板。所有可以看到通用模板定义的代码也应该能够看到特化。否则事情会变得一团糟(程序的不同部分使用不同的代码来调用相同的函数)。

Is what I did more convenient over defining the template functions in .cpp and explicit instantiate to char, int, double, float, and std::string?

没有。除非有具体的理由,否则不要使用显式模板实例化。不要仅仅为了保持头文件精简而使用显式模板实例化。

关于c++ - 如何在头文件和源文件中组织模板函数和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54634797/

相关文章:

c++ - 如何循环链表以减少值?

PHP 将数组传递给函数

javascript - Express.js 路线组织

module - Rust 中的跨模块函数调用

c++ - 优化嵌套循环

c++ - 错误 C3861 : 'aligned' : identifier not found

python - 如何检查字符串是否为 rgb 十六进制字符串

sql-server - 使用 sql management studio 组织存储过程、 View 、函数等

c++ - 将内存分配给类的指针

c++ - 如何将静态库链接到共享库