开发者

How can I ensure that a class has no virtual methods?

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 progr开发者_Python百科am 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.

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.


What would happen if you created a source module which contained a class with the same name as the one where virtual methods were forbidden, and that class contained a virtual method but had no other methods whose names shadowed those of the other class? What global symbols would that class create? My expectation would be that if two classes with the same name exist but don't have anything in common, the linker would probably not squawk, but if both classes have a vtable, the linker might register a conflict. Whether it actually would register a conflict would depend upon the name-mangling rules in use.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜