Should static_assert be triggered with a typedef?

孤者浪人 提交于 2019-12-10 14:33:10

问题


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"

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

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?


回答1:


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

Yes

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.

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

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;

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).



来源:https://stackoverflow.com/questions/11251569/should-static-assert-be-triggered-with-a-typedef

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