Reputation: 17231
I ran into this issue quite a few times. Let's say I have a method:
template <typename T>
bool Foo(T* param)
{
//...
}
If I pass a non-pointer, Visual Studio gives me the error: could not deduce template argument for 'const T *'
but since the code is heavily templated, there is a ton of garbage attached to it (I say garbage because it is not related to the error... i.e. namespaces and template types etc.). Yes, I can tell what is wrong by looking at the message, but it takes that much longer and I think people can relate how that wastes time in the long run.
So I thought I will provide a overload and give a static assertion:
template <typename T>
bool Foo(T param)
{
STATIC_ASSERT_FORCE(Function_does_not_take_a_non_pointer_argument);
}
This works nicely and I get a nice, clear error message. This function is placed just before the definition of the 'correct' function and it becomes immediately clear what I (or whoever is using my code) did wrong and what to do to correct it (that is, call the correct overload).
But that obviously pollutes the method list. Is there any other way to output a better error message?
Upvotes: 4
Views: 67
Reputation: 181815
Instead of only accepting pointers, you could modify your function to accept any type:
template <typename T>
bool Foo(T param)
{
//...
}
In the body, just assume that param
is a pointer. If it isn't, the compiler will complain about operator->
or operator*
being undefined for type T
, and hopefully it'll also tell you what T
's concrete type is.
I'm not sure if this really helps the clarity of your error messages. But it comes with a bonus: your function can suddenly be applied to other pointer-like types as well!
Edit: there might be some SFINAE static-assertion trickery to actually verify that the operators you want are implemented for T
and give a clear error if they're not. Maybe someone else will chime in with a solution for that.
Upvotes: 1