如何在没有C ++ 11的情况下进行编译时断言 [英] How can I make compile time assertions without C++11

查看:124
本文介绍了如何在没有C ++ 11的情况下进行编译时断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在面试中,我被要求写一个元函数
来确定类型是否是一个指针。这是
我提出的:

  template< typename T& 
struct is_pointer
{static const bool value = false; }

template< typename T>
struct is_pointer< T *>
{static const bool value = true; }

然后我被要求写一个meta-assert,在编译时会失败
如果我的 is_pointer 函数不是
做正确的事情。



当我使用 static_assert 时,他明确告诉我
我只能使用C ++ 98标准。

$


p> template< bool> struct assert;
模板<> struct assert< true> {};

会解决这个问题:

  assert<!is_pointer< char> :: value>(); // valid 
assert< is_pointer< char *> :: value>(); // valid

assert< is_pointer< char> :: value>(); //编译错误:
//使用不完整的类


In a job interview, I was asked to write a metafunction that determined whether a type was a pointer. This is what I presented:

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

template <typename T>
struct is_pointer<T *>
{ static const bool value = true; }

Then I was asked to write a meta-assert, that will fail during compile time if my is_pointer function is not doing the right thing.

When I used static_assert, he explicitly told me that I may only use C++98 standard. How can I achieve this?

解决方案

In your case

template <bool> struct assert;
template <> struct assert<true> {};

would have solved the problem:

assert<!is_pointer<char>::value>();     // valid
assert<is_pointer<char *>::value>();    // valid

assert<is_pointer<char>::value>();      // compilation error:
                                        // use of incomplete class

这篇关于如何在没有C ++ 11的情况下进行编译时断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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