首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >typeid中的通配符

typeid中的通配符
EN

Stack Overflow用户
提问于 2010-11-09 02:03:51
回答 4查看 433关注 0票数 2

在我使用的一个库中,有一段代码看起来像这样:

代码语言:javascript
复制
...
     if ( ptype == typeid( Vector< T, 4 > ) )
       {
       This->SetNumberOfComponents(4);
       }
     else if ( ptype == typeid( Vector< T, 5 > ) )
       {
       This->SetNumberOfComponents(5);
       }
...

如果有什么方法可以让它变得更通用,可以这样做

代码语言:javascript
复制
 if ( ptype == typeid( Vector< T, ANYTHING > ) )
       {
       This->SetNumberOfComponents(THE_SECOND_TEMPLATE_PARAM);
       }

谢谢,

大卫

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-11-26 03:58:12

我们接受了Roger Pate的建议,通过稍微调整一下结构来删除typeid的使用(这是第一个评论,所以我不能把它标记为答案)。感谢大家的点子和讨论!

票数 0
EN

Stack Overflow用户

发布于 2010-11-09 02:08:25

你有访问Vector类的权限吗?

如果是这样,您可以在Vector类中添加一个静态字段,它只是回显第二个模板参数:

代码语言:javascript
复制
template<class T, int SIZE>
class Vector
{
   // ...
   public:
      static const int NUM_COMPONENTS = SIZE;
   // ...
};
票数 3
EN

Stack Overflow用户

发布于 2010-11-09 02:50:19

优化编译器会将这个递归定义内联到您的if梯子的等价物中:

代码语言:javascript
复制
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 );
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4126584

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档