C++11 static_assert: Parameterized error messages

不问归期 提交于 2019-12-10 12:48:51

问题


In my previous question I wanted to use static_assert to restrict a template parameter to be a specific subtype. The question was answered, the code for archieving that is as follows:

template <typename T> 
struct X { 
    static_assert(std::is_base_of<Y,T>::value,"T must be derived from Y!");
};

Now, I want to make the error message more concise. I.e., I want to state which type is violating this constraint. E.g., if class A is not derived from Y and someone instanciates X<A>, then the error message should print "The type parameter must be derived from Y, but A isn't".

Is this somehow achievable with the standard library?

I see two challenges:

  • Assembling strings at compiletime without using boost::mpl
  • retrieving the name of the type with which T was instanciated. The name should be meaningful, ideally the same as used in the violating definition. I tried typeid(T).name() but it only returns the mangled name which is not acceptable. I remember that there was some kind of macro that returns the name of something, but I cannot recall that anymore.

回答1:


You cannot do this. static_assert wants a string literal. You have no way to assemble the semantic identity of T and Y into the string literal.

You can hope that the compiler gives an easy to read backtrace of the template instantiation stack and gives you the value of T and Y template parameters of the enclosing class template instantiation.

Other people thought about this too, see http://comments.gmane.org/gmane.comp.compilers.clang.devel/5073 for example.




回答2:


You can still use BOOST_MPL_ASSERT_MSG. It accepts the generic types as parameters and tries to include the concrete type names in the error message.

More information and examples here: http://www.boost.org/doc/libs/1_49_0/libs/mpl/doc/refmanual/assert-msg.html



来源:https://stackoverflow.com/questions/11050511/c11-static-assert-parameterized-error-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!