应该使用typedef触发static_assert吗? [英] Should static_assert be triggered with a typedef?

查看:201
本文介绍了应该使用typedef触发static_assert吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,当实例化 typedef '时,不会触发类模板中的静态断言。

I noticed that static assertions in class templates are not triggered when instantiations are typedef'ed.

#include <type_traits>

template <typename T>
struct test_assert
{
    static_assert( std::is_same< T, int >::value, "should fail" );
};

typedef test_assert< float > t;

此代码无错误地编译。如果我尝试创建一个实例,那么断言失败:

This code compiles without error. If I try to create an instance, then the assertion fails:

t obj; // error: static assertion failed: "should fail"

最后, code> false ,即使我没有实例化类模板,断言也会失败:

Finally, if I replace the condition with false, the assertion fails even if I don't instantiate the class template:

template <typename T>
struct test_assert
{
    static_assert( false, "always fails" );
};

我在gcc-4.5.1和gcc-4.7.0上试过这个代码。这种行为是正常的吗?在什么时候编译器应该验证静态断言?我想两阶段查找涉及,但不应该typedef触发第二阶段?

I tried this code on gcc-4.5.1 and gcc-4.7.0. Is this behavior normal? At what time is the compiler supposed to verify static assertions? I guess two-phase lookup is involved, but shouldn't the typedef trigger the second phase?

推荐答案


我试过这个代码在gcc-4.5.1和gcc-4.7.0。此行为是否正常?

I tried this code on gcc-4.5.1 and gcc-4.7.0. Is this behavior normal?


在什么时候编译器应该验证静态断言?​​

At what time is the compiler supposed to verify static assertions?

这是一个有趣的问题。在实例化期间,这将是非依赖名称的第一阶段查找和依赖于模板参数的断言的第二查找阶段。

This is an interesting question. During instantiation, which will be first phase lookup for non-dependent names and second lookup phase for asserts that depend on template arguments.


猜二相位查找涉及,但不应该typedef触发
第二阶段?

guess two-phase lookup is involved, but shouldn't the typedef trigger the second phase?

模板是按需编译的, typedef只是为模板创建一个别名,并且不会触发实例化。考虑下面的代码:

Templates are compiled on demand, the typedef just creates an alias to the template and does not trigger the instantiation. Consider the following code:

template <typename T> class unique_ptr;
typedef unique_ptr<int> int_unique_ptr;

模板只能声明,但是对于typedef来说是足够的,因为它只会生成一个别名。另一方面,如果你创建一个类型的对象,那么模板必须实例化(再次按需,成员函数不会被实例化)。

The template is only declared, but that suffices for the typedef, as it only generates an alias for the type. On the other side, if you create an object of the type, then the template must be instantiated (again on demand, member functions will not be instantiated).

这篇关于应该使用typedef触发static_assert吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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