Is it possible to get "type of the current struct
" inside of the struct
? For example, I want to do something like this:
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;
}
}
I tried to do it this way:
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;
}
}
but it looks ugly, requires support of the latest C++ Standard, and MSVC connot compile it (it crashes with "an internal error").
Actually, I just want to write some preprocessor macros to auto-generate functions like 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);
}
But I need to know "current type" inside of the macro.
Actually, you can use somethink like this.
#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);
};
I have no idea, how use var. macro-pars in this way (we need to go throw the params and compare each par from this and from t, i have no idea, how expand params in macro).
This stack-overflow URL states that the boost libraries can compute the type of an expression, but C/C++ by itself cannot:
Getting name and type of a struct field from its object
Someone asked a similar question also:
How can I add reflection to a C++ application?
To start using typeof include the typeof header:
#include <boost/typeof/typeof.hpp>
To deduce the type of an expression at compile time use the BOOST_TYPEOF macro:
namespace ex1
{
typedef BOOST_TYPEOF(1 + 0.5) type;
BOOST_STATIC_ASSERT((is_same<type, double>::value));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.