Im writing some helper functions for a project im working on. I’ve always wanted a typeof operator. I know it doesn’t exist in my current IDE (visual studio ’10), so im trying to write an implementation for it. It should work something like this:
auto var = new typeof(<expression>);
It should just be a compile-time retrievable type based off the expression and should be possible. C++ uses this when inducing template arguments, for instance:
template< typename A >
void foo(A unused) {
/* can be invoked like foo(5) with A = int */
typedef A type;
type * used = new type;
}
So i thought i could play around with macroes, classes and templates.. something like this:
#define typeof(expression) (_type_creater().inducer(expression)::type)
template<typename T>
class _type_holder{
public:
typedef T type;
};
class _type_creater{
public:
template< class B >
_type_holder<B> inducer(B _temp) {
/* Here compiler induces the templated expression and creates a typename out of it.
this we can use extract typename from _type_holder, except a instantiatet type apparantly
doesn't have access to typedef'd typenames.
*/
return _type_holder<B>();
}
};
So the problem is basically, that this is illegal:
struct a
{
typedef int type;
}
...
a mya;
new mya::type; //or mya.type
So the first question is, why is this illegal? Why can’t you retrieve typenames from instantiatet types?
Second question, can i do this at all? I tried looking a boosts TYPEOF, but couldn’t make much sense of it, and it seems it just utilizes bugs in VC compilers (“//VC7.0 specific bugfeature”, “//VC8.0 specific bugfeature”, “// This uses nice VC6.5 and VC7.1 bugfeature”).
Am i out of luck?
An object is not a scope. The scope resolution operator (
::) is only applicable to scopes (class scope, namespace scope, global (namespace) scope). I gave a bit of additional information as a theory in a comment on the question.