开发者

Different class version with same name in different files

I have two versions of a same class in two different files (A.cpp, A.h, B.cpp, B.h) in all files the class has the same name but different internal implementation.

My idea is to switch from one version to the other just by changing the name of the .h file at #include, so I shouldn't have to change anything else in the code (both version's methods have the same signature and same properties)

The A.h and B.h are never included at the same time.

The problem is th开发者_JAVA百科at no matter what include file I use always A version is executed. I know that when I include B.h at least it is compiled (by putting some code error they are shown at compilation time)

Can this be done? or this is breaking some rules of C++? I think that this should not break One Definition Rule because I'm not using A.h and B.h at the same time.


The solution is not to link the old file into final executable. That way only the new implementation will be available.


What I'll often do is mangle the version into a namespace, and use that. Something along the lines of:

namespace Xyz_A {   //  In A.h
//  Define version A
}

namespace Xyz = Xyz_A;

; in B.h, use _B instead.

This way, you would write Xyz::... in your program, but the external symbols will have Xyz_A or Xyz_B mangled into them. But in my option, this is really more a protection against errors. I'll arrange things in my makefiles so that whatever switches between A.h and B.h also causes the executable to link against the appropriate library, and not against the other.


If the header files are identical it would be easier just to have one header and 2 different implementations files. That would reduce your problem to just linking with the right object file. This also reduces the chance of subtle bugs should your headers ever diverge.

A better solution would, of course, something that does not depend on the build system but uses language facilities to change code at compile time, like a template.


You will need to load the correct library to match the header file.

I would suggest looking into the proxy design pattern so you can include both class A and B. Then you can use the proxy to choose which class function to use during runtime.

http://en.wikipedia.org/wiki/Proxy_pattern

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜