简体   繁体   English

重载方法只是为了报告C ++中更好的错误。 有没有更好的办法?

[英]Overloading a method just to report a nicer error in C++. Is there a better way?

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... ie namespaces and template types etc.). 如果我传递一个非指针,Visual Studio会给我错误: could not deduce template argument for 'const T *'但由于代码是模板化的,因此附加了大量垃圾(我说垃圾是因为它是与错误无关...即命名空间和模板类型等)。 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? 有没有其他方法可以输出更好的错误消息?

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. 在正文中,假设param是一个指针。 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. 如果不是,编译器会抱怨对于类型T未定义operator->operator* ,并且希望它也会告诉你T的具体类型是什么。

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. 编辑:可能有一些SFINAE静态断言技巧来实际验证您想要的运算符是否为T实现,如果不是则给出明确的错误。 Maybe someone else will chime in with a solution for that. 也许其他人会为此提出解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM