如何检测类是否是C ++ 11中的最终? [英] How to detect if a class is final in C++11?

查看:100
本文介绍了如何检测类是否是C ++ 11中的最终?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码优先。

  #include< iostream> 

using namespace std;

struct A final {};
struct B {};

int main()
{
cout< is_final< A> :: value<< endl; // Output true
cout<< is_final< B> :: value<< endl; //输出false

return 0;
}

如何实现类is_final?类型traits通常使用SFINAE idiom实现,它将一个潜在的错误表达式放置在函数模板声明内。将有问题的类型名替换为声明会导致错误,但是在该上下文中该错误被抑制,因此该声明要么被使用,要么被使用。但是,回退过载会备份潜在的缺少声明。另一位代码访问该函数来检测敏感的重载或仅备份是否被实例化。



这不适用于 final ,因为它只能在类的模板实例化期间导致失败。没有办法重载类,也没有办法暂时定义一个类,它会失败,但不能停止编译,如果它是从最终的。



标准报价,C ++ 11§14.8.2/ 8:


只有在函数类型及其模板参数类型的直接上下文中的无效类型和表达式在扣除失败。 [注意:对替换类型和表达式的评估可能导致副作用,例如类模板专用化和/或函数模板专用化的实例化,隐式定义函数的生成等。这种副作用不在即时上下文,并且可能导致程序不合格。 - end note]



Code first.

#include <iostream>

using namespace std;

struct A final {};
struct B {};

int main()
{ 
    cout << is_final<A>::value << endl; // Output true
    cout << is_final<B>::value << endl; // Output false

    return 0; 
}

How to implement the class is_final?

解决方案

Type traits are usually implemented using the SFINAE idiom, which places a potentially ill-formed expression inside a function template declaration. Substituting the typename in question into the declaration results in an error, but the error is suppressed in that context, so the declaration is either used or not. But a fallback overload backs up the potentially missing declaration. Another bit of code accesses the function to detect whether the sensitive overload or only the backup was instantiated.

This won't work for final because it can only cause failure during template instantiation of a class. There's no way to overload classes, and no way to tentatively define a class that will fail but not halt compilation in case it's derived from final.

Standard quote, C++11 §14.8.2/8:

Only invalid types and expressions in the immediate context of the function type and its template parameter types can result in a deduction failure. [ Note: The evaluation of the substituted types and expressions can result in side effects such as the instantiation of class template specializations and/or function template specializations, the generation of implicitly-defined functions, etc. Such side effects are not in the "immediate context" and can result in the program being ill-formed. — end note ]

这篇关于如何检测类是否是C ++ 11中的最终?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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