rev
rev

Reputation: 1861

Extend templated class to have operator bool on object<bool> instances

I'm trying to extend a template to add a function for a specific type.

This is what I have now:

template<typename T> class Item {
public:
    T value;
}

And I want to make it so Item<bool> has a operator bool(), like this:

template<> class Item<bool> : public Item<bool>{
public:
    explicit operator bool() const {
        return this->value; // error
    }
}

However, I get an error saying class 'Item<bool>' has no member 'value'.

What am I missing?

Upvotes: 1

Views: 369

Answers (3)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

You can't extend template class declarations by introducing arbitrary member function declarations on type specializations.

You need to have that operator declaration appearing in the original class declaration:

template<typename T> class Item {
public:
    T value;
    operator bool() const {
         std::static_assert
            ( !std::is_same<T,bool>
            , "bool conversion is not available for this template parameter type."
            );
    }    
}; // <<< Note the semicolon BTW

and specialize it:

template<> 
Item<bool>::operator bool() const {
    return value;
}

The std::static_assert() will prevent any code from compiling, where you don't like an instantiation to make sense, besides of your own specializations.

Upvotes: 3

Krzysztof Kosiński
Krzysztof Kosiński

Reputation: 4325

The specialized class is not valid, it derives from itself. If you want to include some code in every specialization of a template class, you need to write this differently:

template<typename T> class ItemBase {
public:
    T value;
}

template<typename T> class Item {
    // generic implementation here
}

template<> class Item<bool> : public ItemBase<bool> {
public:
    explicit operator bool() const {
        return this->value;
    }
}

Upvotes: 2

Pradhan
Pradhan

Reputation: 16737

You can't have a class inherit from itself. You might be trying to simulate the openness of classes that you are used to from other languages, e.g,. Python. However, C++ classes are not open - you cannot add to their implementation after defining them. With template classes, this means explicitly specializing the definition for your particular case. Yes, this does require code repetition if you do not design your class hierarchy correctly.

template<> class Item<bool>
{
public:
    bool value;
    explicit operator bool() const {
        return this->value; // error
    }
}

Upvotes: 0

Related Questions