I have a class whose objects are used in shared memory. Therefore, I must be sure that they do not have virtual methods (which crash the program when called via vtable).
I would like to guard against anybody accidentally adding a virtual method in violation of this requirement. Ideally, the compiler would refuse to even compile the class if it contains virtual methods.
Solutions do not necessarily need to be standards compliant, it is sufficient if they work on Apple's gcc-4.2 or MSVC.
How can I achieve this?
Well, I really think this doesn't make sense to enforce, but you could use boost type traits' is_polymorphic or std::is_polymorphic from C++11 onward.
EDIT: Example:
#include <iostream>
#include <boost/type_traits.hpp>
struct Base
{
virtual void MyMethod() { std::cout << "My method called."; }
virtual ~Base() {}
};
class Derived : Base
{
virtual void MyMethod() { std::cout << "Derived"; }
};
struct POD
{
int data;
};
int main()
{
std::cout << boost::is_polymorphic<Base>::value << std::endl;
std::cout << boost::is_polymorphic<Derived>::value << std::endl;
std::cout << boost::is_polymorphic<POD>::value << std::endl;
}
//Output is
// 1
// 1
// 0
//
Add a rule to your source control that rejects check-ins that contain the word 'virtual', sends an email to a senior developer, and docks the pay of the offending party.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With