Sign in to follow this  

specializing of templates

This topic is 3587 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I've come to a situation in my code where I've found it easy to work with a given class if I separate the class's functionality into two separate implementations. I've seen a boolean type used in template interfaces, where the class has different specialized implementations based on the boolean value, which is pretty much what I'm looking for. However, I'm not exactly proficient in using templates yet, so if any of you template gurus can help out, I would appreciate it. :) I currently have something similar to the following code:
template <class T, bool my_flag = true> class MyClass;

template <class T>
class MyClass<T, false>
{
public:
    MyClass();
    ~MyClass();

    void    someFunc1();
    T &     someFunc2(int a);

private:
    T       foo;
};

template <class T>
class MyClass<T, true>
{
public:
    MyClass();
    ~MyClass();

    void    someFunc1();
    T &     someFunc2(int a);

private:
    T       foo;
};

This code actually works just fine, but what bothers me is that I have to declare the same class structure for both specialized cases. However, in my actual class implementation, regardless of the my_flag variable, both classes have exactly the same functions and variables. Both classes have the same constructor/destructor, the same someFunc1(), and the same someFunc2(). Is there any way to simplify this so that I only need to declare my class's interface once?

Share this post


Link to post
Share on other sites
Make a base class templated by T only. Then add boolean specialized descendants.

template < class T >
struct Base {
// all that doesn't relate or bool
};

template < class T, bool b >
struct Derived : public Base<T>
{
// 'false' specific members
};

template < class T >
struct Derived<T, true> : public Base<T>
{
// 'true' specific members
};



And yes, sometimes such approach means duplicating entire interface. See vector<bool>, for example.

Share this post


Link to post
Share on other sites

This topic is 3587 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this