我使用的库中有一段代码如下所示:
...
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);
}
谢谢,
大卫
答案 0 :(得分:3)
您是否可以访问Vector类?
如果是这样,你可以在Vector类中添加一个静态字段,它只是回显第二个模板参数:
template<class T, int SIZE>
class Vector
{
// ...
public:
static const int NUM_COMPONENTS = SIZE;
// ...
};
答案 1 :(得分:2)
优化编译器会将此递归定义内联到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 );
}
答案 2 :(得分:0)
你可能会做一些宏观黑客攻击,所以你不必写太多重复的代码。
#include <boost/preprocessor/repetition/repeat.hpp>
#include <typeinfo>
#include <iostream>
struct X
{
void SetNumberOfComponents(int n) { std::cout << n << '\n'; }
};
template <class T, int N>
struct Vector{};
typedef int T;
void foobar(const std::type_info& ptype)
{
#define SUPPORTED_VECTOR_TYPES 20
#define BRANCH(z, n, text) else if (ptype == typeid(Vector<T, n>)) {This->SetNumberOfComponents(n);}
X x;
X* This = &x;
if (0); BOOST_PP_REPEAT(SUPPORTED_VECTOR_TYPES, BRANCH, UNUSED)
#undef SUPPORTED_VECTOR_TYPES
#undef BRANCH
}
int main()
{
foobar(typeid(Vector<int, 10>));
}
答案 3 :(得分:0)
我们采取了Roger Pate的建议,即通过稍微重组来取消对typeid的使用(这是第一个评论,因此我无法将其标记为答案)。感谢所有伟大的想法和讨论!