在C ++中组织实用函数 [英] Organising utility functions in C++
问题描述
我有3个小(每行15行)功能功能,什么是最好的方式来组织他们?
I have 3 smallish (15 lines each) utilitity functions, whats the best way to organise them? put them in their own namespace in a header file?
推荐答案
创建一个名为 utility.hpp的单独文件
并将所有的函数声明放在其中,最好在自己的命名空间下,可以只是 utility
,然后将定义放在 utility.cpp
。如果任何效用函数是函数模板,你必须把定义放在头本身。
Create a separate file called utility.hpp
and put all the function declarations in it, preferably under its own namespace which could be just utility
, and then put the definitions in utility.cpp
. If any of the utility functions is function template, you've to put the definition in the header itself.
避免定义实用程序 class
并把所有的效用函数作为 static
成员。这是一个坏主意。其中一个原因是,它不能利用参数依赖名称查找( ADL )。
Avoid defining utility class
and putting all the utility functions in it as static
members. That is seriously a bad idea. One reason for it being bad, is that it cannot take advantage of Argument Dependent name Lookup (ADL).
使用命名空间。
示例,
//utility.hpp
namespace utility
{
void function1();
void function2();
void function3();
template<typename T>
void function4()
{
//function template definition should be here!
}
}
然后,
//utility.cpp
#include "utility.hpp"
namespace utility
{
void function1()
{
//code
}
void function2()
{
//code
}
void function3()
{
//code
}
}
这篇关于在C ++中组织实用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!