简体   繁体   中英

Is there any way to emulate meta programming in C++?

Is there any way to emulate meta programming in C++ ? ( c++ not c++11 standard) For Python on stack suggests ( Generate specific names proeprties using metaclass ) me to create like and it works

class FooMeta(type):
    def __init__(cls, name, bases, dct):
        super(FooMeta, cls).__init__(name, bases, dct)
        for n in range(100):
           setattr(cls, 'NUMBER_%s'%n, n)

class Bar(object):
    __metaclass__ = FooMeta

But I also need same class in C++, class with n static const int NUMBER_some_number fields. How to create this without hardcoding ?

In Python naming the first few hundred integers can have a slight performance advantage, since a typical implementation only caches a few hundred integers, and there's still a look-up for them.

In C++ integers are not dynamic objects so there is no problem and no advantage.

In C++ meta programming is now typically done by using the template mechanism. Before that was introduced one used macros to generate code. However, since the Python problem that you're addressing doesn't exist in C++, there's no point.

As "Cheers and hth. - Alf" pointed out there is no performance gain when you do the same thing in c++. Moreover it would be really absolutely bad style that should be avoided at all costs. It is like not programming in c++ at all.

If for some reason you still cannot avoid doing that you could use Boost.Preprocessor :

#include <boost/preprocessor/iteration/local.hpp>

#define BOOST_PP_LOCAL_MACRO(n) \
    static const int NUMBER_ ## n = n;

// NOTE the valid range you can iterate over has to be a subset of [0, BOOST_PP_LIMIT_ITERATION]
#define BOOST_PP_LOCAL_LIMITS (0, 99)

class Bar
{
    public:
#include BOOST_PP_LOCAL_ITERATE()
};

You can see the expanded result when calling for example

g++ -E file.h

where file.h is the file you put your code in.

One note though. Things like Boost.Preprocessor should not be overused as that again would be bad style Macros can be quite useful, but I try to avoid them as much as possible.

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