C++中只有静态方法的类的优点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7345956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:48:12  来源:igfitidea点击:

Advantages of classes with only static methods in C++

c++static

提问by dcn

Even though there are no static classes in C++, coming from a Java background I use to create a helper class like Utilcontaining only static methods. Is this considered bad styleor usual practice? One alternative I see is to use C functions (no class context at all). What other alternatives are there? What are there advantages and disadvantages and under which circumstances would I use any of these.

尽管C++没有静态类,但来自 Java 背景,我使用它来创建一个助手类,例如Util只包含静态方法。这被认为是糟糕的风格还是惯常的做法?我看到的一种替代方法是使用 C 函数(根本没有类上下文)。还有哪些其他选择?有什么优点和缺点,在什么情况下我会使用这些。

defining bunch of static methods in c++suggests namespacing static functions as one alternative, though I fail to see what effects the statickeyword without class context has.

在 C++ 中定义一堆静态方法建议将命名空间静态函数作为一种替代方法,尽管我没有看到static没有类上下文的关键字有什么影响。

回答by James O'Doherty

If you want to create a collection of utility functions without clobbering the global namespace, you should just create regular functions in their own namespace:

如果你想在不破坏全局命名空间的情况下创建一组实用函数,你应该只在它们自己的命名空间中创建常规函数:

namespace utility {
    int helper1();
    void helper2();
};

You probably don't want to make them static functions either. Within the context of a non-member function (as opposed to a member function), the static keyword in C and C++ simply limits the scope of the function to the current source file (that is, it sort of makes the function private to the current file). It's usually only used to implement internal helper functions used by library code written in C, so that the resulting helper functions don't have symbols that are exposed to other programs. This is important for preventing clashes between names, since C doesn't have namespaces.

您可能也不想让它们成为静态函数。在非成员函数(与成员函数相反)的上下文中,C 和 C++ 中的 static 关键字只是将函数的范围限制在当前源文件中(也就是说,它使函数对当前文件)。它通常只用于实现由 C 编写的库代码使用的内部辅助函数,因此生成的辅助函数没有暴露给其他程序的符号。这对于防止名称之间的冲突很重要,因为 C 没有名称空间。

回答by Nawaz

In C++, classes with onlystaticmethods is mostly used in template metaprogramming.

在 C++ 中,只有static方法的类主要用于模板元编程。

For example, I want to calculatefibonacci numbers at compile-timeitself, and at runtime I want them to print only, then I can write this program:

例如,我想在编译时计算斐波那契数,而在运行时我只想打印它们,然后我可以编写这个程序:

#include <iostream>

template<int N>
struct Fibonacci 
{
   static const int value = Fibonacci<N-1>::value + Fibonacci<N-2>::value;
   static void print()
   {
       Fibonacci<N-1>::print();
       std::cout << value << std::endl;
   }
};


template<>
struct Fibonacci<0>
{
   static const int value = 0;
   static void print()
   {
       std::cout << value << std::endl;
   }
};

template<>
struct Fibonacci<1>
{
   static const int value = 1;
   static void print()
   {
       Fibonacci<0>::print();
       std::cout << value << std::endl; 
   }
};

int main() {
        Fibonacci<20>::print(); //print first 20 finonacci numbers
        return 0;
}

Online demo : http://www.ideone.com/oH79u

在线演示:http: //www.ideone.com/oH79u

回答by Tony The Lion

C++ is a multi paradigm language, so if you need some util functions that perhaps don't really fit in a class at all, then I would just make them free functions. I don't see a reason to put them into a class, just for OOP's sake.

C++ 是一种多范式语言,因此如果您需要一些可能根本不适合类的实用程序函数,那么我会让它们成为自由函数。我认为没有理由将它们放入一个类中,只是为了 OOP。

There is no advantage that I can see to making all functions staticand putting them in a class, over having them just as free functions. Personally, I think free functions are then an easier to work with option.

我认为制作所有函数static并将它们放在一个类中,而不是将它们作为自由函数使用并没有什么优势。就个人而言,我认为免费功能是一个更容易使用的选项。

回答by Darren Engwirda

As many others have pointed out, free functions inside a namespace is an approach that's often taken for this sort of thing in c++.

正如许多其他人指出的那样,命名空间内的自由函数是c++.

One case I'd make for classes with all static functions is when you'd like to expose a set of functions to information derived from template parameters, i.e.

我为具有所有静态函数的类所做的一种情况是,当您希望将一组函数公开给从模板参数派生的信息时,即

template <typename Ty>
    class utils
{
public :
// if you need to setup a bunch of secondary types, based on "Ty" that will be used 
// by your utility functions
    struct item_type
    { 
        Ty data;
        // etc
    }; 

// a set of utilities
    static void foo(Ty &data1, item_type &item)
    { 
        // etc
    }
};

You can use this to achieve the effect of a template'd namespace:

您可以使用它来实现模板命名空间的效果:

int main ()
{
    double data;
    utils<double>::item_type item ;
    utils<double>::foo(data, item);

    return 0;
}

If you're not using templates just stick with namespaces.

如果您不使用模板,请坚持使用名称空间。

Hope this helps.

希望这可以帮助。

回答by Puppy

In C++, just make them free functions. There's no need or reason to place them in a class at all. Unless you're doing shizzle with templates.

在 C++ 中,只需将它们设为自由函数即可。根本没有必要或理由将它们放在一个班级中。除非你对模板很着迷。

回答by EddieBytes

There is no real issue with declaring static methods within a class. Although namespaces are more suitable for this purpose for the reasons mentioned in the post you are referring to.

在类中声明静态方法没有实际问题。尽管出于您所指的帖子中提到的原因,名称空间更适合于此目的。

Using C functions can generate name collisions, unless you decide on a naming convention, prefixing your functions with stuff, for example btFunctionA, btFunctionB etc. You will want to keep your symbols within namespaces to avoid that, you are using C++ and not C after all.

使用 C 函数会产生名称冲突,除非你决定命名约定,在你的函数前面加上一些东西,例如 btFunctionA、btFunctionB 等。你会希望将你的符号保留在命名空间中以避免这种情况,你使用的是 C++ 而不是 C全部。

Static functions within a namespace aren't any different from non-static. I believe the static keyword is simply ignored in this context.

命名空间中的静态函数与非静态函数没有任何区别。我相信 static 关键字在这种情况下被简单地忽略了。

回答by Matt

This may be relevant to your interests. It is an article that, uh, examines the different approaches to classes and functions in Java compared to other languages.

这可能与您的兴趣有关。这篇文章,呃,研究了与其他语言相比,Java 中类和函数的不同方法。

http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html

http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html

回答by dc42

There is one other situation in which a static class might be preferred to a namespace: when you want to make the data private so that it can't be directly modified from outside the class/namespace, but for performance reasons you want to have have public inlinefunctions that operate on it. I don't think there is any way to do that with a namespace, other than by declaring a class inside the namespace.

在另一种情况下,静态类可能比命名空间更受欢迎:当您希望将数据设为私有以便不能从类/命名空间外部直接修改它时,但出于性能原因,您希望拥有对其进行操作的公共内联函数。我认为除了在命名空间内声明一个类之外,没有任何方法可以使用命名空间来做到这一点。