在我使用的一个库中,有一段代码看起来像这样:
...
if ( ptype == typeid( Vector< T, 4 > ) )
{
This->SetNumberOfComponents(4);
}
else if ( ptype == typeid( Vector< T, 5 > ) )
{
This->SetNumberOfComponents(5);
}
...如果有什么方法可以让它变得更通用,可以这样做
if ( ptype == typeid( Vector< T, ANYTHING > ) )
{
This->SetNumberOfComponents(THE_SECOND_TEMPLATE_PARAM);
}谢谢,
大卫
发布于 2010-11-26 03:58:12
我们接受了Roger Pate的建议,通过稍微调整一下结构来删除typeid的使用(这是第一个评论,所以我不能把它标记为答案)。感谢大家的点子和讨论!
发布于 2010-11-09 02:08:25
你有访问Vector类的权限吗?
如果是这样,您可以在Vector类中添加一个静态字段,它只是回显第二个模板参数:
template<class T, int SIZE>
class Vector
{
// ...
public:
static const int NUM_COMPONENTS = SIZE;
// ...
};发布于 2010-11-09 02:50:19
优化编译器会将这个递归定义内联到您的if梯子的等价物中:
template<typename T, size_t N>
struct TestType {
static void Test ( const std::type_info& ptype ) {
if ( ptype == typeid ( Vector< T, N > ) )
This->SetNumberOfComponents ( N );
else
TestType < T, N - 1 >::Test ( ptype );
}
};
// need to have a base case which doesn't recurse
template<typename T>
struct TestType<T, 0> {
static void Test ( const std::type_info& ptype ) {}
};
const size_t MAX_DIMENSIONS ( 12 );
template<typename T>
void SetNumberOfComponents ( VectorBase<T>* p )
{
const std::type_info& ptype ( typeid ( *p ) );
TestType<T, MAX_DIMENSIONS>::Test ( ptype );
}https://stackoverflow.com/questions/4126584
复制相似问题