Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I enforce that a template parameter used implements some interface in C++?

I don't think this is possible in C++, what options do I have to simulate the behavior?

like image 232
dchhetri Avatar asked Nov 30 '22 04:11

dchhetri


2 Answers

Use std::is_base_of as:

template<typename T>
class A
{
    static_assert(std::is_base_of<IMyInterface, T>::value, 
                  "T must derive from IMyInterface");
};

You can same in function template as well.

like image 133
Nawaz Avatar answered Dec 04 '22 12:12

Nawaz


You can use std::is_base_of<YourInterface, YourParameter>, and make an error if the result is false. Remember this is C++11.

like image 20
Synxis Avatar answered Dec 04 '22 13:12

Synxis