开发者

Take a reference to a class template'd on any type

I'm writing C++ code that takes a reference to a class that depends on specific hardware, firmware and drivers. I would like to stub out the interface for testing, but there are a few roadblocks that have me stumped. The class I'm interfacing with is auto-generated (not my idea) so I can't have it inherit from a base class that defines the interface. The methods I need to call aren't virtual so my test stub can't inherit from it and override the methods.

It occurred to me that I could create a wrapper class that's templated and just redirect the call to the class that it's typed on. I would have something like...

template< class T >
class DriverInterface
{
    public:
        DriverInterface( T& driverImpl ):
        m_driverImpl( driverImpl )
        {
        }

        virtual ~DriverInterface( void )
        {
        }

        virtual void GetDataBuffer( char *&pData, int &bufLen )
        {
            m_driverImpl.GetDataBuffer( pData, bufLen );
        }

        virtual void WriteDataBuffer( char *pData, int bufLen )
        {
            m_driverImpl.WriteDataBuffer( pData, bufLen );
        }
    protected:
        T& m_driverImpl;

    private:
};

class DriverWriter
{
    pu开发者_StackOverflow中文版blic:
        DriverWriter( DriverInterface& driverInterface );
    //etc
}

Unfortunately the compiler wants me to specify a type parameter on DriverInterface in my DriverWriter class. Is there a way to restructure the code so that I don't need to specify the type?


A common way to solve it is to factor out the virtual functions into their own interface that doesn't depend on template parameters:

class DriverInterfaceBase
{
    public:
        virtual ~DriverInterfaceBase( void ) { }

        virtual void GetDataBuffer( char *&pData, int &bufLen ) = 0;
        virtual void WriteDataBuffer( char *pData, int bufLen ) = 0;
};

// Derive from it:
template< class T >
class DriverInterface : public DriverInterfaceBase

You can then write

class DriverWriter
{
    public:
        DriverWriter( DriverInterfaceBase& driverInterface );
    //etc
};
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜