Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template specialization with types which have certain interface

Suppose I have such template:

template<class T>
class A
{
   ...
};

I want this template can be specialized only if type which will be substituted in place of T have certain interface. For example, this type must have such two methods:

int send(const char* buffer, size_t size);
int receive(char* buffer, size_t size);

How can i make this restrictions on the template? Thanks for the help!

UPD:

This question is about SFINAE? not about inheretince or class design.

like image 772
Kirill Chernikov Avatar asked Apr 25 '26 12:04

Kirill Chernikov


1 Answers

The very easy way is to use T::send and T::receive within A, any type not implementing those will result in a compile time failure to instantiate the template. You only need SFINAE to distinguish between specialisations of templates.

e.g.

template<class T>
class A
{
    void useT(T & theT)
    {
        char buf[20]
        theT.send("Some Thing", 11);
        theT.recieve(buf, 20);
    }
};
like image 125
Caleth Avatar answered Apr 27 '26 02:04

Caleth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!