Filipe Carvalho
Filipe Carvalho

Reputation: 628

Class name by define directive. Possible?

Can I create a class and assign his name from an external source?

ex:

// Something like this
#define ClassName Clients

class ClassName
{
    public:
    ClassName();
};

ClassName::ClassName()
{
    //
}

Edit: my real code (That way, in the XML output of the DUnit framework, my the test name is TestName, not DatabaseTest)

#define TestName DatabaseTest

namespace TestName
{
    class TTest : public TTestCase
    {
        public:
        __fastcall virtual TTest(System::String name) : TTestCase(name)
        {
        }
        virtual void __fastcall SetUp();
        virtual void __fastcall TearDown();

        __published:
        void __fastcall t1();
    };

    void __fastcall TTest::SetUp()
    {
    }

    void __fastcall TTest::TearDown()
    {
    }

    void __fastcall TTest::t1()
    {
        CheckEquals(1,0);
    }
}

class TTestName : public TestName::TTest
{

};

static void registerTests()
{
    Testframework::RegisterTest(TTestName::Suite());
}

Upvotes: 0

Views: 901

Answers (2)

Shahbaz
Shahbaz

Reputation: 47583

Although absolutely not recommended, it is possible. The C (or C++) preprocessors replace whatever name they can with the specified defined value without caring for their meaning. After all, they are just preprocessors.

So, say you have this header file:

generic_class.h

class ClassName
{
    public:
    ClassName()
    {
        //
    }
};

You can get multiple instances of this class like this:

#define ClassName Server
#include "generic_class.h"
#undef ClassName

#define ClassName Clients
#include "generic_class.h"
#undef ClassName

Note that you should not add guards to the header.

This code is terrible of course.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258638

Yes. Pre-processing takes place before compilation.

Your compiler will basically see

class Clients
{
    public:
    Clients();
};

Clients::Clients()
{
    //
}

But why would you want this? Is there some underlying issue you're trying to solve? I'm sure there are better ways.

Upvotes: 1

Related Questions