'助手'在C ++中的功能 [英] 'Helper' functions in C++

查看:82
本文介绍了'助手'在C ++中的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在重构一些旧代码时,我已经删除了一些公共方法,应该实际上是静态的,因为他们a)不操作任何成员数据或调用任何其他成员函数和b),因为他们可能证明有用的其他。



这让我想到了将帮助器函数组合在一起的最好方法。 Java / C#的方式是使用一个带有私有构造函数的静态函数类,例如:

  class Helper 
{
private:
Helper(){}
public:
static int HelperFunc1();
static int HelperFunc2();
};但是,使用C ++也可以使用命名空间:


$ b

$ b

 命名空间助手
{
int HelperFunc1();
int HelperFunc2();
}



在大多数情况下,我想我更喜欢命名空间方法,每种方法的优点和缺点。如果使用类方法,例如,会有任何开销吗?

解决方案

开销不是一个问题,命名空间有一些优势,




  • 您可以在另一个标题中重新打开命名空间,更逻辑地分组事件,而
    保持编译依赖性低

  • 您可以使用命名空间别名来获得优势
    (debug / release,platform specific helpers,....)



    我做了像

     命名空间LittleEndianHelper {
    void Function
    }
    namespace BigEndianHelper {
    void Function();
    }


    #if powerpc
    命名空间Helper = BigEndianHelper;
    #elif intel
    命名空间Helper = LittleEndianHelper;
    #endif



While refactoring some old code I have stripped out a number of public methods that should actually of been statics as they a) don't operate on any member data or call any other member functions and b) because they might prove useful elsewhere.

This led me to think about the best way to group 'helper' functions together. The Java/C# way would be to use a class of static functions with a private constructor, e.g.:

class Helper  
{  
private:  
  Helper() { }
public:  
  static int HelperFunc1();  
  static int HelperFunc2();  
};

However, being C++ you could also use a namespace:

namespace Helper  
{  
  int HelperFunc1();  
  int HelperFunc2();  
}

In most cases I think I would prefer the namespace approach but I wanted to know what the pros and cons of each approach are. If used the class approach for example, would there be any overheads?

解决方案

Overhead is not an issue, namespaces have some advantages though

  • You can reopen a namespace in another header, grouping things more logically while keeping compile dependencies low
  • You can use namespace aliasing to your advantage (debug/release, platform specific helpers, ....)

    e.g. I've done stuff like

    namespace LittleEndianHelper {
       void Function();
    }
    namespace BigEndianHelper {
       void Function();
    }
    
    
    #if powerpc
       namespace Helper = BigEndianHelper;
    #elif intel
       namespace Helper = LittleEndianHelper;
    #endif
    

这篇关于'助手'在C ++中的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆