- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我使用带有标志 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/
假设我在 net.aserve 和 bordeaux-threads 之上构建了一个应用程序。我的包声明可能如下所示: (defpackage :my-package (:use :cl :net
我是一名优秀的程序员,十分优秀!