简体   繁体   中英

Adding methods to class template specialization

I would like to achieve behaviour present in STL: when we look at a vector container, it is known that it has vector<bool> specialization which adds method flip() .

Is it possible to achieve such class extension without copying the whole class as a specialization and adding new method in its body?

I suppose you can write the specialization so it inherit from the generic version.

By example: suppose you have a struct foo with a type and a value (with default value) template parameters; suppose it has some methods ( bar() , in the following example)

template <typename, bool = true>
struct foo 
 { void bar () {}; };

and suppose you want a specialization for bool (as template type) with the same methods and an additional baz() ; you can inherit foo<bool> from the general version as follows

template <>
struct foo<bool> : public foo<bool, false>
 { void baz () {}; };

You can verify that

   foo<int>   fi;

   fi.bar();   // compile
   //fi.baz(); // compilation error

   foo<bool>  fb;

   fb.bar();  // compile
   fb.baz();  // compile

You can SFINAE the method of "specialization"

template <typename T>
class C
{
public:
    // Common code...

    template <typename U = T, std::enable_if_t<std::is_same<bool, U>::value, bool> = false>
    void only_for_bool() {/*..*/}
};

C++20 would allow better syntax:

template <typename T>
class C
{
public:
    // Common code...

    void only_for_bool() requires (std::is_same<bool, T>::value) {/*..*/}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM