static_assert - 一种动态自定义错误消息的方法 [英] static_assert - a way to dynamically customize error message

查看:725
本文介绍了static_assert - 一种动态自定义错误消息的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让static_assert的字符串被动态自定义然后显示?

我的意思是:

  //伪代码
static_assert(Check_Range< T> :: value,value of+ typeof(T)+type is not good)。


解决方案

不,没有。



然而,这并不重要,因为 static_assert 在编译时被评估,如果发生错误,编译器不仅会打印消息本身,但它也将打印instanciation堆栈(如​​果是模板)。



看看这个合成例子 in ideone

  #include< iostream> 

template< typename T>
struct IsInteger {static bool const value = false; };

模板<>
struct IsInteger< int> {static bool const value = true; };

template< typename T>
void DoSomething(T t){
static_assert(IsInteger< T> :: value,// 11
not an integer);

std :: cout<< t;
}

int main(){
DoSomething(Hello,World! // 18
}

编译器不仅发出诊断,完整堆栈:

  prog.cpp:在函数'void DoSomething(T)[with T = const char *]' 
prog.cpp:18:30:从这里实例化
prog.cpp:11:3:error:static assertion failed:不是整数

如果你知道Python或Java以及如何在异常情况下打印堆栈,应该是熟悉的。事实上,它甚至更好,因为你不仅得到调用堆栈,但你也得到参数值(这里的类型)!



因此,动态消息不是必要的:)


Is there a way to make static_assert's string being dynamically customized and then displayed?
What I mean is something like:

//pseudo code
static_assert(Check_Range<T>::value, "Value of " + typeof(T) + " type is not so good ;)");

解决方案

No, there is not.

However this does not matter so much, because static_assert are evaluated at compile-time, and in case of error the compiler will not only print out the message itself, but it will also print the instanciation stack (in case of templates).

Have a look at this synthetic example in ideone:

#include <iostream>

template <typename T>
struct IsInteger { static bool const value = false; };

template <>
struct IsInteger<int> { static bool const value = true; };

template <typename T>
void DoSomething(T t) {
  static_assert(IsInteger<T>::value, // 11
  "not an integer");

  std::cout << t;
}

int main() {
  DoSomething("Hello, World!"); // 18
}

The compiler does not only emits the diagnostic, but it also emits the full stack:

prog.cpp: In function 'void DoSomething(T) [with T = const char*]':
prog.cpp:18:30:   instantiated from here
prog.cpp:11:3: error: static assertion failed: "not an integer"

If you know Python or Java and how they print the stack in case of exception, it should be familiar. In fact, though, it's even better, because you not only get the call stack, but you also get the arguments values (types here)!

Therefore, dynamic messages are not as necessary :)

这篇关于static_assert - 一种动态自定义错误消息的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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