Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent templated member function from being instantiated for a given type

I have a templated matrix class that I explicitly instantiate for various POD types and custom class types. Some of the member functions however don't make sense for a few of such custom types. For example:

Matrix<int> LoadFile(....); // This makes sense
Matrix<My_custom_class> LoadFile(...); //This doesn't make sense in the context of the custom class

Can I prevent the instantiation of the LoadFile function (which is a member function) for Matrix objects of select types? So far I have avoided the issue by making LoadFile a friend function and then explicitly controlling its instantiation. But I want to know if I can do this when LoadFile is a member function of Matrix.

like image 274
deepak Avatar asked Feb 17 '23 01:02

deepak


1 Answers

The first question is whether you really need to control this. What happens if they call that member function on a matrix that stores My_custom_class? Can you provide support in your class (or the template) so that the member function will work?

If you really want to inhibit the use of those member functions for some particular type, then you can use specialization to block the particular instantiation:

template <typename T>
struct test {
   void foo() {}
};
template <>
inline void test<int>::foo() = delete;

Or even just add static_asserts to the common implementation verifying the preconditions for what types is it allowed or disallowed?

template <typename T>
struct test {
   void foo() {
       static_assert(std::is_same<T,int>::value || std::is_same<T,double>::value,
                     "Only allowed for int and double");
       // regular code
   }
};
like image 92
David Rodríguez - dribeas Avatar answered May 09 '23 18:05

David Rodríguez - dribeas