C ++ 11 static_assert:参数化的错误消息 [英] C++11 static_assert: Parameterized error messages

查看:187
本文介绍了C ++ 11 static_assert:参数化的错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的上一个问题我想使用static_assert来将模板参数限制为特定的子类型。问题回答,archieving的代码如下:

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!");
};

现在,我想让错误消息更简洁。也就是说,我想说明哪种类型违反了这个约束。例如,如果类 A 不是从 Y 派生的,并且有人建议 X< A> / code>,那么错误消息应该打印类型参数必须从Y派生,但 A 不是。

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?

我看到两个挑战:


  • 在compiletime中组装字符串,而不使用boost :: mpl

  • 检索与T类型相同的类型的名称。名称应该是有意义的,理想地与违反定义中使用的相同。我尝试了typeid(T).name(),但它只返回不合格的名称。我记得有一些宏返回了一些东西的名字,但我不记得了。

推荐答案

你不能这样做。 static_assert 想要一个字符串文字。您没有办法将 T Y 的语义标识组合到字符串文字中。

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.

您可以希望编译器提供一个容易读取的模板实例化堆栈的回溯,并给出 T Y 封装类模板实例化的模板参数。

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.

其他人也想到了, a href =http://comments.gmane.org/gmane.comp.compilers.clang.devel/5073> http://comments.gmane.org/gmane.comp.compilers.clang.devel/5073 a>。

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

这篇关于C ++ 11 static_assert:参数化的错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆