How to stop template class for a type | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to stop template class for a type

Hi How to avoid error in attached code ? I just want to avoid the template class for int... How to do same ? https://code.sololearn.com/coV5FijP5pN9/?ref=app

27th May 2022, 8:17 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Answers
+ 5
There are several ways to do this. For such a simple case, you can just use static_assert to assert that T is not int https://code.sololearn.com/ct9GQv6sPd8O/?ref=app There are a lot of cases where you have several partial specialisations of the template, in which case you might want to choose one specialization over another. There, a static_assert won't be enough. Before C++ 20, the way to do this was to use std::enable_if https://code.sololearn.com/cTmooXtM9MRO/?ref=app After C++ 20, you can use template constraints which offer a much better syntax and error message (compared to the mess that std::enable_if emits on failure) https://code.sololearn.com/ctWvsPop4hY8/?ref=app std::enable_if :- https://en.cppreference.com/w/cpp/types/enable_if Template constraints: https://en.cppreference.com/w/cpp/language/constraints
27th May 2022, 9:51 AM
XXX
XXX - avatar
+ 1
I don't know if = delete syntax is available for classes/structures, I would do as follows: template<> struct myClass<int> { private: myClass() {} }; This way you could not instantiate myClass<int> objects. For static functions you could simply leave the specialization empty, so display() wouldn't exist for myClass<int>.
27th May 2022, 9:36 AM
OrHy3
OrHy3 - avatar
+ 1
Thanks XXX and OrHy3
27th May 2022, 10:03 AM
Ketan Lalcheta
Ketan Lalcheta - avatar