Johannes
Johannes

Reputation: 6717

implicitly specializing template class without the use of <>

I am extracting dependencies from a codebase using templates. In doing so the new classes are template classes now. I want to initialise them just like before. Otherwise I would have to touch parts of my production code before I have tests in place.

Here is a minimal example:

#include <iostream>
using namespace std;

//OLD SOURCE
class LogUser_Old
{
public:
    void print() { cout << "LogUser Old" << endl; }
};

//NEW SOURCE
struct normal 
{
    static void log(const char * out) { cout << out << endl; }
};

struct injected
{
    static void log(const char * out) { cout << "injected '" << out << "'" << endl; }
};

template< typename output = normal>
class LogUser_New
{
public:
    void print() { output::log("LogUser New"); }
};

int main()
{
    //OLD Production Code
    LogUser_Old lo;
    lo.print();
    //New Production Code
    LogUser_New<> ln; //THE <> is a change in Production code
    ln.print();
    //Testcode
    LogUser_New<injected> ln_silent;
    ln_silent.print();
    return 0;
}

Here LogUser was rewritten to be injectable. _Old marks the old state _New marks the new state. The previous Production code used to instantiate the class has to be updated from LogUser user; to LogUser<> user;.

Is there a way to make the compiler implicitly figure out that he can use the empty template case here so the production code can remain just the same as before?

Upvotes: 2

Views: 27

Answers (1)

Yes, use a typedef:

template< typename output = normal>
class LogUser_New_tmpl
{
public:
    void print() { output::log("LogUser New"); }
};

typedef LogUser_New_tmpl<> LogUser_New;

If you have C++11, you can of course use using instead of typedef:

using LogUser_New = LogUser_New_tmpl<>;

Upvotes: 1

Related Questions