gpt4 book ai didi

c++ - 即使无处调用模板函数,static_assert 也会编译失败

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:40:32 25 4
gpt4 key购买 nike

我使用带有标志 c++0x 的 g++ 4.6.3(目前是 ubuntu 12.04 的默认包),我偶然发现了这个:

template <typename T>
inline T getValue(AnObject&)
{
static_assert(false , "this function has to be implemented for desired type");
}

编译错误:

static_assertion failed "this function has to be implemented for the desired type"

即使我还没有在任何地方调用这个函数

这是 g++ 错误吗?只有在代码中的某处调用此函数时,才应实例化此函数。

最佳答案

标准在 [temp.res]/8 中说

No diagnostic shall be issued for a template definition for which a valid specialization can be generated. If no valid specialization can be generated for a template definition, and that template is not instantiated, the template definition is ill-formed, no diagnostic required. ... [ Note: If a template is instantiated, errors will be diagnosed according to the other rules in this Standard. Exactly when these errors are diagnosed is a quality of implementation issue. — end note ]

无法实例化将编译的函数模板,因此模板定义格式错误,因此允许(但不是必需)编译器拒绝它,即使它没有被实例化也是如此。

你可以让它像这样工作:

template<typename T>
struct foobar : std::false_type
{ };

template <typename T>
inline T getValue(AnObject&)
{
static_assert( foobar<T>::value , "this function has to be implemented for desired type");
}

现在编译器不能立即拒绝函数模板,因为在它被实例化之前它不知道是否会有 foobar 的特化。有 value == true .当实例化 foobar<T> 的相关特化时将被实例化,静态断言仍然会根据需要失败。

关于c++ - 即使无处调用模板函数,static_assert 也会编译失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51888944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com