2012-07-25 6 views
5

È possibile ottenere "il tipo di corrente struct" all'interno di struct? Per esempio, voglio fare qualcosa di simile:Come ottenere informazioni su "tipo corrente" all'interno di una struttura/classe?

struct foobar { 
    int x, y; 

    bool operator==(const THIS_TYPE& other) const /* What should I put here instead of THIS_TYPE? */ 
    { 
    return x==other.x && y==other.y; 
    } 
} 

ho cercato di fare in questo modo:

struct foobar { 
    int x, y; 

    template<typename T> 
    bool operator==(const T& t) const 
    { 
    decltype (*this)& other = t; /* We can use `this` here, so we can get "current type"*/ 
    return x==other.x && y==other.y; 
    } 
} 

ma sembra brutto, richiede il supporto dei più recenti C++ standard, e MSVC connot compilalo (si blocca con "un errore interno").

realtà, voglio solo scrivere alcune macro di preprocessore per funzioni di auto-generare come operator==:

struct foobar { 
    int x, y; 
    GEN_COMPARE_FUNC(x, y); 
} 

struct some_info { 
    double len; 
    double age; 
    int rank; 
    GEN_COMPARE_FUNC(len, age, rank); 
} 

Ma ho bisogno di sapere "di tipo corrente" all'interno della macro.

+1

Perché non basta fare la macro GEN_COMPARE_FUNC (foobar, x, y) invece? – Rollie

+0

@ForEveR tramite 'Macro Variadic'. È supportato da GCC e MSVC, quindi è abbastanza per me. – qehgt

+0

Usando un operatore bool di tipo == ', potresti accidentalmente rendere possibile il confronto di due tipi in cui non ha senso che siano comparabili. –

risposta

0

In realtà, è possibile utilizzare qualcosa come questo.

#define GEN_COMPARE_FUNC(type, x, y)\ 
template<typename type>\ 
bool operator ==(const type& t) const\ 
{\ 
    return this->x == t.x && this->y == t.y;\ 
} 

struct Foo 
{ 
    int x, y; 
    GEN_COMPARE_FUNC(Foo, x, y); 
}; 

Non ho idea, come usare var. macro-pars in questo modo (dobbiamo andare a lanciare i parametri e confrontare ogni par da questo e da t, non ho idea di come espandere i parametri in macro).

0

Questo URL di stack overflow afferma che le librerie Boost in grado di calcolare il tipo di espressione, ma C/C++ da solo non può:

Getting name and type of a struct field from its object

Qualcuno ha chiesto una domanda simile anche:

How can I add reflection to a C++ application?

Per iniziare a utilizzare typeof includono l'intestazione typeof:

#include <boost/typeof/typeof.hpp> 

di dedurre il tipo di un'espressione al momento della compilazione utilizzare la macro BOOST_TYPEOF:

namespace ex1 
{ 
    typedef BOOST_TYPEOF(1 + 0.5) type; 

    BOOST_STATIC_ASSERT((is_same<type, double>::value)); 
} 
+0

C++ 11 can. typedef decltype (1 + 0.5) type; – ForEveR

Problemi correlati