Template "Adapters" in C++
I am currently facing a problem dealing with template classes. In the codebase I am currently working with we have a line something like this:
Register<uint32_t>* myReg = static_cast<Register<uint32_t>*>(importItemPtr(someGlobalIdString));
where importItemPtr is responsible for returning a void* to an item from some global collection based on an identifying string.
The problem is that this code now will be running on a platform where the object referred to by someGlobalIdString will no longer be of type Register<uint32_t>
, but instead Register<uint64_t>
. This is a decision that must be made at runtime. Since I'm using templatized types I can't have a single pointer that can point to either a Register<uint32_t>
or a Register<uint64_t>
. So I must either
- Have two copies of the class that imports this register, one that handles types of uint32_t and one that handles types of uint64_t. This solution obviously sucks because of the code duplication.
- Templatize the class that imports this register. In a开发者_高级运维n ideal world this is probably the correct solution but it doesn't really fit the "normal way of doing things" and the rest of the coworkers would probably prefer copy and paste over templatizing this type of class.
- Make an adapter. Subclass
Register<uint64_t>
to create a new class that accepts aRegister<uint32_t>
as a constructor and essentially just wraps that register and returns 64 bit values instead of 32. Rewrite the consuming class to always use the 64 bit version and when we're on the platform that provides the 32 bit version just wrap it. The code segment above would look something like this:
The adapter:
class Reg32to64Adapter : public Register<uint64_t> { ... }
The consuming class:
Register* myReg;
if( is32bitPlatform )
{
Register* my32Reg = static_cast*>(importItemPtr(someGlobalIdString));
myReg = new Reg32to64Adapter(my32Reg);
}else
{
myReg = static_cast*>(importItemPtr(someGlobalIdString));
}
//Go on manipulating myReg
Is there a better solution out there? Some design pattern I don't know about?
Try to use Bridge pattern where Implementor is a collection of common operations and specialization are ConcreteImplementors.
http://en.wikipedia.org/wiki/Bridge_pattern
Probably not best solution (overdesign), so please analyse it before use.
精彩评论