简体   繁体   English

c ++类列表,无需初始化即可使用静态函数

[英]c++ List of classes without initializing them for use of static functions

I may be asking this in a odd way, but I'm not sure how else to ask. 我可能以一种奇怪的方式问这个问题,但是我不确定还有什么要问的。

I want to have a list of classes, not objects. 我想要一个类列表,而不是对象。 This way I can call static functions without have to create the object. 这样,我无需创建对象就可以调用静态函数。

I would really prefer function pointers at this point: 在这一点上,我真的更喜欢函数指针:

struct A
{
  void SomeFunc(int);
};

struct B
{
  void AnotherFunc(int);
};


typedef void (*Function)(int);

std::vector<Function> vec;

vec.push_back(A::SomeFunc); vec.push_back(B::AnotherFunc);

for (Function f: vec)
{
  f(2);
}

Note that a static function is more or less equivalent to a traditional C-function (it just got to access some more scope). 请注意,静态函数或多或少等效于传统的C函数(它只是需要访问更多作用域)。

What you are looking for are boost typelists . 您正在寻找的是boost类型列表 I would however not recommend diving into the Boost MPL if you are not already very experienced with templates, and know how many of their intricacies work. 我不过不推荐潜入了Boost MPL如果你是不是已经非常有经验的模板,并知道有多少他们的复杂工作。

Now for a simple home-made implementation: 现在进行简单的自制实现:

struct Null {};

template <typename Type, typename Next>
struct List
{
  typedef Type Type;
  typedef Next Next;
};

//Now you can make lists like so:
typedef List<int, List<float List<short, Null> > > MyList;

From there use recursive Templated implementations to call the static methods you want. 从那里使用递归模板化实现来调用所需的静态方法。

If you want more information on these kinds of techniques, you should read Modern C++ Design 如果您想了解有关这些技术的更多信息,请阅读Modern C ++ Design

作为解决方案,您可以创建方法指针列表

I don't think what you are asking is possible, at least not in the way you think. 我认为您的要求是不可能的,至少不会以您的想法。 You cannot have a variable, array, container class or any other storage of type names. 您不能具有变量,数组,容器类或类型名称的任何其他存储。 So you cannot do something like 所以你不能做这样的事情

ListOfClasses[n]::someStaticMember(...);

in C++. 在C ++中。 It is impossible. 是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM