Compile time if-else statement

Following Modern C++.

#include <iostream>

using namespace std;

template<int v>
struct int2type
{
    enum { value = v };
};

template<typename T, int NeedArgument>
class Factory
{
private:
    T* create(int2type<false>)
    {
        cout << "new T" << endl;
        return new T;
    }

    T* create(int2type<true>)
    {
        cout << "new T(\"hi\")" << endl;
        return new T("hi");
    }

public:
    T* create() { return create(int2type<NeedArgument>()); }
};

int main()
{
    Factory<string, false> f;
    Factory<string, true> f2;

    string* s = f.create();
    cout << *s << endl;
    delete s;

    s = f2.create();
    cout << *s << endl;
    delete s;

    return EXIT_SUCCESS;
}

[output]
C:\> a.exe
new T

new T(“hi”)
hi
Hit any key to close this window…

int2type class was used to convert the given parameter into type parameter. According to the type of int2type, proper method for creating T is called.

Post a Comment

Your email is never published nor shared.

Spam protection by WP Captcha-Free