lundi 26 septembre 2016

Enforce template function to be T=B* inside a class

I have a storage class, it can add/remove element.

Most of its public functions share a very similar signature as shown function :-

template<class T> class Storage{
    public: void add(T& t){ ... }
    //... other fields,functions
}

A great thing is that T can be value or raw pointer.

Now I want to upgrade this storage to support T=std::unique_ptr too.
This is what I want to accomplish:-

Storage<std::unique_ptr<B>> store;
B* b = new B();
store.add(b);   //my attempt
//^ This call seem to be not appropriate, but this is what I want

Here is my draft :-

template<class T> class Storage{
    public: template<class TWeak> void add(TWeak& tw){
        ...
    }
}

From the draft, I think it is somewhat dangerous to use TWeak as a template argument - TWeak can be anything.

It is contradict to my intention that TWeak can only be T's weakpointer , roughly speaking.

More specifically, I want to enforce this rule :-

When   T=std::unique_ptr<B>   ==>    TWeak have to be B* or std::unique_ptr<B>
When   T=B*                   ==>    TWeak have to be B*
When   T=B                    ==>    TWeak have to be B

How to enforce the rules elegantly?

Aucun commentaire:

Enregistrer un commentaire