È 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.
Perché non basta fare la macro GEN_COMPARE_FUNC (foobar, x, y) invece? – Rollie
@ForEveR tramite 'Macro Variadic'. È supportato da GCC e MSVC, quindi è abbastanza per me. – qehgt
Usando un operatore bool di tipo == ', potresti accidentalmente rendere possibile il confronto di due tipi in cui non ha senso che siano comparabili. –