Lee Jacobs
Lee Jacobs

Reputation: 1757

Obtaining names of functions at compile time?

I'd like to make a small and stupid test framework.

One requirement I would like to fulfill in creating this stupid framework is the ability to add any functions that start with "TEST_" to my function list and one function each for "SETUP_" and "TEARDOWN_".

For example:

TEST_MyFirstTest("My fake test"){
   //... test code
}

SETUP_MyTest("setup before each test"){
   //... create all objects to be handled here
}

int main() {
   TESTFRAMEWORK Test = new TESTFRAMEWORK();
   Test.run();
   return 0;
}

Obviously I'd define my tests in a separate file, but is there a way to do this? Would I need to use TMP?

Upvotes: 1

Views: 214

Answers (1)

dspeyer
dspeyer

Reputation: 3026

If you're willing to tweak the syntax to:

TEST(MyFirstTest, "My Fake Test") {
  // test code...
}

Then you could do something like:

struct testBase {                                                     
  virtual void run() = 0;                                             
  virtual const char* getDesc() = 0;                                  
};                                                                   

vector<testBase*> global_test_collection;                            

#define TEST(name,desc)                                               \
struct test_##name : public testBase {                                \
  virtual void run();                                                 \
  virtual const char* getDesc() { return desc; }                      \
  static bool init;                                                   \
};                                                                    \
test_##name::init = global_test_collection.append(new test_##name()); \
void test_##name::run()

I haven't actually tested this.

You might be able to simplify it by using function pointers instead of virtual functions, but you'd lose the descriptions and might run into issues with what order you do things in.

Upvotes: 1

Related Questions