Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 是否应使用typedef触发static_断言?_C++_Templates_Static Assert - Fatal编程技术网

C++ 是否应使用typedef触发static_断言?

C++ 是否应使用typedef触发static_断言?,c++,templates,static-assert,C++,Templates,Static Assert,我注意到类模板中的静态断言在实例化typedef时不会触发 #include <type_traits> template <typename T> struct test_assert { static_assert( std::is_same< T, int >::value, "should fail" ); }; typedef test_assert< float > t; 最后,如果我将条件替换为false,则即使我没有实

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

#include <type_traits>

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

typedef test_assert< float > t;
最后,如果我将条件替换为
false
,则即使我没有实例化类模板,断言也会失败:

template <typename T>
struct test_assert
{
    static_assert( false, "always fails" );
};
模板
结构测试断言
{
静态_断言(false,“总是失败”);
};
我在gcc-4.5.1和gcc-4.7.0上尝试了这段代码。这种行为正常吗?编译器应该在什么时候验证静态断言?我猜需要两阶段查找,但是typedef不应该触发第二阶段吗

我在gcc-4.5.1和gcc-4.7.0上尝试了这段代码。这种行为正常吗

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

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

我猜可能涉及两阶段查找,但typedef不应该触发吗 第二阶段

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

template <typename T> class unique_ptr;
typedef unique_ptr<int> int_unique_ptr;
模板类唯一性\u ptr;
typedef unique_ptr int_unique_ptr;

只声明了模板,但这对于typedef就足够了,因为它只生成类型的别名。另一方面,如果您创建了该类型的对象,则必须实例化模板(同样,根据需要,成员函数将不会实例化)。

谢谢,这就是我的想法。我很惊讶,因为在几个月的模板元编程中,我从未注意到这一点。实际上,在TMP中,
typedef
s通常访问嵌套类型,触发实例化。好问题。:-)
template <typename T> class unique_ptr;
typedef unique_ptr<int> int_unique_ptr;