Re: Is this kind of static polymorphism valid?
On 2012-09-05 17:02, DeMarcus wrote:
What I want to do is an ultra-light (syntax-wise) yet powerful TDD
framework. It looks like the following. It should compile but it's
possible that the self-registering doesn't run perfectly due to the
initialization order thing. This is just to show you the idea.
[snip code]
Also another question I have is why I can't put the specialized
runTests() function within the unnamed namespace as well? I get the
following error from gcc 4.7.1.
runTests() must be defined in the namespace where it was declared,
i.e., the same namespace as MyTestFixture<T>.
I don't see what benefit your approach has over plain-old polymorphism
like:
// ITestFixture.hpp
#pragma once
class ITestFixture
{
public:
static std::vector<ITestFixture*> testFixtures;
virtual ~ITestFixture() {}
virtual void runAllTests() = 0;
};
// MyTestFixture.hpp
#pragma once
#include <vector>
#include <string>
#include <functional>
#include <iostream>
#include "ITestFixture.hpp"
class MyTestFixture : public ITestFixture
{
public:
MyTestFixture( const std::string& name )
{
// This is a self-registering object.
testFixtures.push_back( this );
std::cout << "Registering: " << name << std::endl;
}
protected:
void test( std::function<void()> function )
{
function();
}
};
// FreeFunctions1Test.cpp
// !!! NOTE, it's a CPP file !!!
//
// This file will be multiplied and specialized for all the
// different unit tests.
#include "MyTestFixture.hpp"
namespace
{
class FreeFunctionTestFixture : public MyTestFixture
{
public:
FreeFunctionTestFixture() : MyTestFixture( "Free Functions 1" )
{}
private:
void runAllTests()
{
test(
[&]
{
std::cout << "Test 1 for Free Functions 1" << std::endl;
});
test(
[&]
{
std::cout << "Test 2 for Free Functions 1" << std::endl;
});
}
};
FreeFunctionTestFixture tst;
}
// main.cpp
#include <vector>
#include "ITestFixture.hpp"
std::vector<ITestFixture*> ITestFixture::testFixtures;
int main()
{
for( auto fixture : testFixtures )
fixture->runAllTests();
return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]