When using templates we can have T
be any type upon class instantiation. If T
is a specific type that needs to be handled differently or in a special way we can specialize or partial specialize that class template
.
What if we want T
to be any type except for specific types that we don't want it to allow?
With this in mind, I was thinking of making use of either the !
or !=
operator(s) or more as them being tokens within this context as far as the compiler(s) would be concerned to prevent the class template
from using that type...
Here's an example of what the syntax would look like:
template<typename T, T !=char, T !=unsigned char>
// or
template<typename T, T !char, T !unsigned char>
// This means that T can be anything but char and unsigned char!
struct Foo {
T value;
};
Then:
Foo<int> f1; // Okay
Foo<float> f2; // Okay
Foo<char> f3; // Would fail to compile generating the appropriate error message or
// would just delete that instance as if it was never declared
// and generate compiler errors for all code that would try to use it.
This could also be extended or expanded to work with user-defined types
as well...
I believe that this could allow for simplifying a lot of code allowing the programmer to explicitly fine-tune and restrict their code usage to their users, that it is easy to read with direct intent shown, and that it would be fairly easy for the compilers to implement without breaking already existing code bases by adding in this feature.
Would this be something that you would find useful and practical?
enable_if
is for (especially when combined with operator!
). There is already plenty of code that uses this technique - you can easily find it and learn the many ways to use it. In fact, check this tutorial out.