简体   繁体   中英

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).

What you are looking for are boost typelists . 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.

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

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

http://www.boost.org/doc/libs/1_45_0/libs/mpl/doc/refmanual/refmanual_toc.html

eg:

typedef vector<C1,C2,C3> types;
at_c<types,0>::type::method();
...

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++. It is impossible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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