Domanda

V'è una sezione di codice in un uso io libreria che assomiglia a questo:

...
     if ( ptype == typeid( Vector< T, 4 > ) )
       {
       This->SetNumberOfComponents(4);
       }
     else if ( ptype == typeid( Vector< T, 5 > ) )
       {
       This->SetNumberOfComponents(5);
       }
...

Se c'è un modo per rendere questo più generico facendo qualcosa di simile

 if ( ptype == typeid( Vector< T, ANYTHING > ) )
       {
       This->SetNumberOfComponents(THE_SECOND_TEMPLATE_PARAM);
       }

Grazie,

David

È stato utile?

Soluzione 4

Abbiamo preso il suggerimento di Roger Pate di eliminare l'utilizzo di typeid ristrutturando un po '(E' stato il primo commento, quindi non ho potuto segnarlo come la risposta). Grazie per tutte le grandi idee e la discussione!

Altri suggerimenti

Non si ha accesso alla classe Vector?

Se è così, è possibile aggiungere un campo statico all'interno della classe Vector che semplicemente riecheggia il secondo parametro di template:

template<class T, int SIZE>
class Vector
{
   // ...
   public:
      static const int NUM_COMPONENTS = SIZE;
   // ...
};

un compilatore ottimizzato sarà inline questa definizione ricorsiva nell'equivalente della vostra se scaletta:

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 );
}

Si potrebbe probabilmente fare un po 'un po' di hacking macro, in modo da non dover scrivere codice troppo ripetuti.

#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>));
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top