你不能定义 SetData(vector),因为 std::vector 需要一个类型,如果你没有 T 的定义,你显然不能在 Base 中定义 SetData(std::vector< T >)。
所以如果你真的需要这个并且认为这是要走的路,你将不得不研究类型调度(或使用 void* 进行破解)。Boost 在某些地方使用类型调度,否则谷歌提供示例。
编辑它的外观的简单示例;不是真正的类型调度,而是更直接
class Base
{
public:
template< class T >
bool SetData( const std::vector< T >& t )
{
return SetData( static_cast< const void* >( &t ), typeid( t ) );
}
protected:
virtual bool SetData( const void*, const std::type_info& ) = 0;
};
template< class T >
class Derived : public Base
{
protected:
bool SetData( const void* p, const std::type_info& info )
{
if( info == typeid( std::vector< T > ) )
{
const std::vector< T >& v = *static_cast< const std::vector< T >* >( p );
//ok same type, this should work
//do something with data here
return true;
}
else
{
//not good, different types
return false;
}
}
};