Method overload to report a more pleasant bug in C ++. Is there a better way?

I came across this question several times. Let's say I have a method:

template <typename T> bool Foo(T* param) { //... } 

If I pass in a non-pointer, Visual Studio will give me an error: could not deduce template argument for 'const T *' , but since the code is very dark, there is a ton of garbage attached to it (I say “garbage” because it is not connected to error ... i.e. namespaces, template types, etc.). Yes, I can say that it is not so by looking at the message, but it takes much more time, and I think that people can tell how it spends time in the long run.

So, I thought I would provide an overload and give a static statement:

 template <typename T> bool Foo(T param) { STATIC_ASSERT_FORCE(Function_does_not_take_a_non_pointer_argument); } 

This works well and I get a nice, clear error message. This function is placed immediately before the definition of the “correct” function, and it immediately becomes clear that I (or someone who uses my code) did wrong, and what needs to be done to fix it (that is, cause the correct overload).

But this clearly pollutes the list of methods. Is there any other way to output a better error message?

+4
source share
1 answer

Instead of accepting pointers, you can change your function to accept any type:

 template <typename T> bool Foo(T param) { //... } 

In the body, just assume that param is a pointer. If this is not the case, the compiler will complain about operator-> or operator* on undefined for type T , and hopefully it will also tell you what T specific type.

I'm not sure if this really helps clarity of your error messages. But it comes with a bonus: your function may suddenly apply to other types of pointers!


Edit: there might be some trick of the SFINAE static statement to make sure that the operators you need are implemented for T and give a clear error if they are not. Maybe someone else will talk with a solution for this.

+1
source

Source: https://habr.com/ru/post/1397226/


All Articles