Jump to content
  • Advertisement
Sign in to follow this  
Falken42

specializing of templates

This topic is 3869 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!