Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a class is final in C++11?

Tags:

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?

like image 838
xmllmx Avatar asked Dec 10 '12 21:12

xmllmx


People also ask

Is final a keyword in C?

Final keyword have the following purposes in C++ Note: the main difference with final keyword in Java is , a) final is not actually a keyword in C++. you can have a variable named as final in C++ b) In Java, final keyword is always added before the class keyword.

How do you mark a class final in C++?

2nd use of final specifier: final specifier in C++ 11 can also be used to prevent inheritance of class / struct. If a class or struct is marked as final then it becomes non inheritable and it cannot be used as base class/struct. The following program shows use of final specifier to make class non inheritable: CPP.

How do you check if an object is an instance of a class C++?

C++ has no direct method to check one object is an instance of some class type or not. In Java, we can get this kind of facility. In C++11, we can find one item called is_base_of<Base, T>. This will check if the given class is a base of the given object or not.

What is the use of the finally keyword in C++?

Grammar. The try-finally statement is a Microsoft extension to the C and C++ languages that enable target applications to guarantee execution of cleanup code when execution of a block of code is interrupted. Cleanup consists of such tasks as deallocating memory, closing files, and releasing file handles.


1 Answers

As the implementer of GCC's __is_final intrinisic (for PR 51365) I'm pretty sure it can't be done in a library, it needs compiler support.

You can do some very clever things with C++11's SFINAE for expressions feature but to detect whether a class is final you'd need to derive from it, and instantiate the derived type, in a template argument deduction context, but deriving from a class is done in a declaration not an expression.

Also, you should think about whether you only want to know if the final pseudo-keyword was used, or if a class is un-derivable for other reasons, such as having only private constructors.

like image 200
Jonathan Wakely Avatar answered Sep 17 '22 13:09

Jonathan Wakely