Is there some way in C++11 or higher to achieve a similar behavior to:
int some_int;
std::string x=variable_name<some_int>::value; //Theoretical code
std::cout << x;
Result should be:
some_int
If not, is there a compiler specific way to do it? I am targeting MSVS.
You ask:
Is there some way in C++11 or higher to achieve a similar behavior to:
int some_int;
std::string x=type_name<some_int>::value; //Theoretical code
std::cout << x;
Result should be:
some_int
Yes, you can just use the preprocessor's stringizing operator #:
#include <iostream>
#define NAME_OF( v ) #v
using namespace std;
auto main() -> int
{
int some_int;
//std::string x=type_name<some_int>::value; //Theoretical code
auto x = NAME_OF( some_int );
(void) some_int;
cout << x << endl;
}
If you're asking for something different, then please post a new question since this one has now been answered (amending the question would invalidate this answer).
As an example real world usage, here's macro to pass a variable and its name to a test function:
#define TEST( v ) test( v, #v )
If you want a compile time check that the name in question is a variable or type name, then you can simply apply sizeof, e.g. in a comma expression:
#define NAME_OF( v ) (sizeof(v), #v)
The difference between having sizeof or not, is whether this is guaranteed to be done purely at compile time, versus possibly generating code to also do something at run time.
To avoid a possible warning you can add a pseudo-cast to void:
#define NAME_OF( v ) ((void) sizeof(v), #v)
And to make this work also for a function name you can add a typeid:
#define NAME_OF( name ) ((void) sizeof(typeid(name)), #name)
Complete example:
#include <typeinfo>
#define NAME_OF( name ) ((void) sizeof(typeid(name)), #name)
void foo() {}
#include <iostream>
using namespace std;
auto main() -> int
{
int some_int;
(void) some_int;
//std::string x=type_name<some_int>::value; //Theoretical code
auto v = NAME_OF( some_int );
auto t = NAME_OF( int );
auto f = NAME_OF( foo );
#ifdef TEST_CHECKING
(void) NAME_OF( not_defined );
#endif
cout << v << ' ' << t << ' ' << f << endl;
}
The checking is not 100% perfect, though, because it's still possible to pass a function invocation to the NAME_OF macro.
As others have pointed out, you can indeed use a macro to "stringify" the variable name. However, instead of simply defining it as #define NAMEOF(variable) #variable, you can use the following definition:
#define NAMEOF(variable) ((decltype(&variable))nullptr, #variable)
As you can see, it uses a comma operator. The left part of this expression does nothing but performs a (pointless) conversion from nullptr to a pointer to variable's type, the result of which gets immediately discarded. The right part simply returns the stringified variable's name.
Why is this better than simply using #variable in the macro?
Thanks to the decltype() operator, the whole thing will only compile if you pass a variable of some sort and not some arbitrary string or a literal to NAMEOF macro. Consider the following example:
double value = 523231231312.0095;
cout<< NAMEOF(value) << endl; // value
cout<< NAMEOF(value1) << endl; // Compiler error: 'value1' was not declared in this scope
cout<< NAMEOF(42) << endl; // Compiler error: lvalue required as unary '&' operand
Because of this, if during future refactoring you modify the name of value variable, you won't forget to also modify places, where you use its name, since compiler will scream at you, until you also fix every usage of NAMEOF for this variable.
Tested on MinGW-W64 (gcc v5.2.0)
In the comments, #iammilind and #Niall have suggested two other ways to define this macro, which don't rely on C++11-specific decltype() operator:
#define NAMEOF(variable) ((void*)&variable, #variable)
...or...
// Unlike other definitions, this one, suggested by #Niall,
// won't get broken even if unary & operator for variable's type
// gets overloaded in an incompatible manner.
#define NAMEOF(variable) ((void)variable, #variable)
// On the other hand, it accepts literals as parameters for NAMEOF,
// though this might be desired behaviour, depending on your requirements.
NAMEOF(42); // 42
Using such a macro with #Leon's suggestion, based on your comments, we get:
template<class T>
void foo(T var, const char* varname)
{
std::cout << varname << "=" << var << std::endl;
}
#define FOO(var) foo(var, NAMEOF(var))
int someVariable = 5;
FOO(someVariable); // someVariable = 5
FOO(nonExistingVariable); // compiler error!
As follows from the comments, you need it for passing into a function both the value of the variable and its name. This must be done with the help of a macro:
#include <iostream>
template<class T>
void foo(T var, const char* varname)
{
std::cout << varname << "=" << var << std::endl;
}
#define FOO(var) foo(var, #var)
int main()
{
int i = 123;
double d = 45.67;
std::string s = "qwerty";
FOO(i);
FOO(d);
FOO(s);
return 0;
}
Output:
i=123
d=45.67
s=qwerty
Related
I want to print out a function pointer using cout, and found it did not work.
But it worked after I converting the function pointer to (void *), so does printf with %p, such as
#include <iostream>
using namespace std;
int foo() {return 0;}
int main()
{
int (*pf)();
pf = foo;
cout << "cout << pf is " << pf << endl;
cout << "cout << (void *)pf is " << (void *)pf << endl;
printf("printf(\"%%p\", pf) is %p\n", pf);
return 0;
}
I compiled it with g++ and got results like this:
cout << pf is 1
cout << (void *)pf is 0x100000b0c
printf("%p", pf) is 0x100000b0c
So what does cout do with type int (*)()? I was told that the function pointer is treated as bool, is it true?
And what does cout do with type (void *)?
Thanks in advance.
EDIT: Anyhow, we can observe the content of a function pointer by converting it into (void *) and print it out using cout.
But it does not work for member function pointers and the compiler complains about the illegal conversion. I know that member function pointers is rather a complicated structure other than simple pointers, but how can we observe the content of a member function pointers?
There actually is an overload of the << operator that looks something like:
ostream & operator <<( ostream &, const void * );
which does what you expect - outputs in hex. There can be no such standard library overload for function pointers, because there are infinite number of types of them. So the pointer gets converted to another type, which in this case seems to be a bool - I can't offhand remember the rules for this.
Edit: The C++ Standard specifies:
4.12 Boolean conversions
1 An rvalue of arithmetic,
enumeration, pointer, or pointer to
member type can be converted to an
rvalue of type bool.
This is the only conversion specified for function pointers.
Regarding your edit, you can print out contents of anything by accessing it via unsigned char pointer. An example for pointers to member functions:
#include <iostream>
#include <iomanip>
struct foo { virtual void bar(){} };
struct foo2 { };
struct foo3 : foo2, foo { virtual void bar(){} };
int main()
{
void (foo3::*p)() = &foo::bar;
unsigned char const * first = reinterpret_cast<unsigned char *>(&p);
unsigned char const * last = reinterpret_cast<unsigned char *>(&p + 1);
for (; first != last; ++first)
{
std::cout << std::hex << std::setw(2) << std::setfill('0')
<< (int)*first << ' ';
}
std::cout << std::endl;
}
You can think of a function pointer as being the address of the first instruction in that function's machine code. Any pointer can be treated as a bool: 0 is false and everything else is true. As you observed, when cast to void * and given as an argument to the stream insertion operator (<<), the address is printed. (Viewed strictly, casting a pointer-to-function to void * is undefined.)
Without the cast, the story is a little complex. For matching overloaded functions ("overload resolution"), a C++ compiler gathers a set of candidate functions and from these candidates selects the "best viable" one, using implicit conversions if necessary. The wrinkle is the matching rules form a partial order, so multiple best-viable matches cause an ambiguity error.
In order of preference, the standard conversions (and of course there also user-defined and ellipsis conversions, not detailed) are
exact match (i.e., no conversion necessary)
promotion (e.g., int to float)
other conversions
The last category includes boolean conversions, and any pointer type may be converted to bool: 0 (or NULL) is false and everything else is true. The latter shows up as 1 when passed to the stream insertion operator.
To get 0 instead, change your initialization to
pf = 0;
Remember that initializing a pointer with a zero-valued constant expression yields the null pointer.
In C++11 one could modify this behavior by defining a variadic template overload of operator<< (whether that is recommendable or not is another topic):
#include<iostream>
namespace function_display{
template<class Ret, class... Args>
std::ostream& operator <<(std::ostream& os, Ret(*p)(Args...) ){ // star * is optional
return os << "funptr " << (void*)p;
}
}
// example code:
void fun_void_void(){};
void fun_void_double(double d){};
double fun_double_double(double d){return d;}
int main(){
using namespace function_display;
// ampersands & are optional
std::cout << "1. " << &fun_void_void << std::endl; // prints "1. funptr 0x40cb58"
std::cout << "2. " << &fun_void_double << std::endl; // prints "2. funptr 0x40cb5e"
std::cout << "3. " << &fun_double_double << std::endl; // prints "3. funptr 0x40cb69"
}
Casting pointers to (void*) to print them to cout is the right thing (TM) to do in C++ if you want to see their values.
Regarding your specific question,
how can we observe the content of a
member function pointers?
The answer is, other than converting them to bool to express that it points to something or it doesn't, you can't 'observer' member function pointers. At least not in a compliant way. The reason is because the standard explicitly disallows this:
4.12 footnote 57:
57) The rule for conversion of
pointers to members (from pointer to
member of base to pointer to member of
derived) appears inverted compared to
the rule for pointers to objects (from
pointer to derived to pointer to base)
(4.10, clause 10). This inversion is
necessary to ensure type safety. Note
that a pointer to member is not a
pointer to object or a pointer to
function and the rules for conversions
of such pointers do not apply to
pointers to members. In particular, a
pointer to member cannot be converted
to a void*.
For example, here is sample code:
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
class Gizmo
{
public:
void DoTheThing()
{
return;
};
private:
int foo_;
};
int main()
{
void(Gizmo::*fn)(void) = &Gizmo::DoTheThing;
Gizmo g;
(g.*fn)(); // once you have the function pointer, you can call the function this way
bool b = fn;
// void* v = (void*)fn; // standard explicitly disallows this conversion
cout << hex << fn;
return 0;
}
I note that my debugger (MSVC9) is able to tell me the actual physical address of the member function at runtime, so I know there must be some way to actually get that address. But I'm sure it is non-conformant, non-portable and probably involves machine code. If I were to go down that road, I would start by taking the address of the function pointer (eg &fn), casting that to void*, and go from there. This would also require you know the size of pointers (different on different platforms).
But I would ask, so long as you can convert the member-function pointer to bool and evaluate the existance of the pointer, why in real code would you need the address?
Presumably the answer to the last question is "so I can determine if one function pointer points to the same function as another." Fair enough. You can compare function pointers for equality:
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
class Gizmo
{
public:
void DoTheThing()
{
return;
};
**void DoTheOtherThing()
{
return;
};**
private:
int foo_;
};
int main()
{
void(Gizmo::*fn)(void) = &Gizmo::DoTheThing;
Gizmo g;
(g.*fn)(); // once you have the function pointer, you can call the function this way
bool b = fn;
// void* v = (void*)fn; // standard explicitly disallows this conversion
cout << hex << fn;
**void(Gizmo::*fnOther)(void) = &Gizmo::DoTheOtherThing;
bool same = fnOther == fn;
bool sameIsSame = fn == fn;**
return 0;
}
maybe (in one time I stay intersecting about the address of function)
one of decision )))
#include <iostream>
#include <stdlib.h>
void alexf();
int main()
{
int int_output;
printf("printf(\"%%p\", pf) is %p\n", alexf);
asm( "movl %[input], %%eax\n"
"movl %%eax, %[output]\n"
: [output] "+m" (int_output)
: [input] "r" (&alexf)
: "eax", "ebx"
);
std::cout<<"" <<std::hex<<int_output <<""<<std::endl;
return 0;
}
void alexf() { }
passing the pointer to function (&alexf) or other pointer using & use constraint r. Let gcc to use register for input argument)).
I have read many times on the difference between decltype(x) and decltype((x)). One example is as per below.
x is the name of a variable, so decltype(x) is int. But wrapping the name x in parentheses—“(x)”—yields an expression more complicated than a name. Being a name, x is an lvalue, and C++ defines the expression (x) to be an lvalue, too. decltype((x)) is therefore int&. Putting parentheses around a name can change the type that decltype reports for it!
Can someone show me the output of a variable say x where the output type of decltype(x) and decltype((xx)) are different? I need an example explicitly showing difference in output.
Appreciate that.
Thanks.
If you declare a variable with type decltype((x)), it is a reference. The easiest way to see the difference is probably this:
int x = 0;
decltype(x) copy = x; // creates an int which is a copy of x
decltype((x)) ref = x; // creates a reference to x
ref = 7; // changes x
copy = 99; // does not change x
std::cout << x << '\n'; // prints 7
std::cout << copy << '\n'; // prints 99
std::cout << ref << '\n'; // prints 7
As for when you would use decltype((x)), I hesitate to say never, but I can say that I've never had a reason to do it in my own code.
Let's say we have int a = 0, then decltype(a) would be int, since a directly names the entity. decltype((a)), on the other hand, should be int&, since (a) is an expression that does not refer directly to the entity.
The same holds for members as well, for example:
#include <iostream>
#include <type_traits>
struct S {
int v = 0;
};
int main() {
S s;
std::cout << std::is_same<decltype(s.v), int>() << std::endl;
std::cout << std::is_same<decltype((s.v)), int&>() << std::endl;
}
decltype(s.v) is int, since s.v directly refers to the name of an entity. decltype((s.v)), on the other hand, is int&. (s.v) does not refer directly to the name of the entity.
A while ago I asked about std::string constants correct idiom for std::string constants?.
What I took away from that was not to use std::string constants but to use char string constants. So what the best idiom for that
#define FOO "foo"
const char * const FOO = "foo";
const char FOO[] = "foo";
Desirable features
get length at compile time. 1 & 3 but
not 2 (sizeof doesnt work on 2)
can be included in .h without linker
complaining. all (I think)
no multiple copies in .o, in linked
output. depends on compiler
(probably)
So it seems like #3 is best but scott meyers says to use #2 (effective c++ item #1)
summary of answers
use jolly complicated template code
use #3
The template code feels like overkill. So for now I go with #3;
But I will ruminate on the template code, the macroized version makes it look OKish; but I dont like the fact that its not portable (who knows, maybe gcc will decide that its wrong too)
For the features that you want, ...
get length at compile time,
can be included in .h without linker complaining all,
no multiple copies in .o, in linked output,
... you can use the templated constant idiom, like
template< class Dummy >
struct Foo_
{
static char const s[];
};
template< class Dummy >
char const Foo_<Dummy>::s[] = "Blah blah";
typedef Foo_<void> Foo; // Now you can refer to Foo:s
#include <iostream>
using namespace std;
int main()
{
cout << sizeof( Foo::s ) << " bytes: \"" << Foo::s << "\"\n";
}
You can wrap the generation in a macro.
However, as far as I know the only practical utility is to support char/wchar_t-agnostic code, and for that the pain may be larger than the gain.
EDIT:
MSVC versions 7.1 up through 10.0 incorrectly doesn't accept the sizeof. The following is a workaround that compiles nicely with g++ 4.4.1, Comeau Online 4.3.10.1, MSVC 7.1 and MSVC 10.0.
#include <stddef.h>
typedef ptrdiff_t Size;
// Substitute a more general countOf
template< Size n >
struct SizedBuf { char sizer[n]; };
template< class Type, Size n >
SizedBuf< n > countOf_( Type (&)[n] ) { return n; }
#define COUNT_OF( array ) sizeof( countOf_( array ).sizer )
#define DEF_STRING( name, value ) \
template< class > \
struct name##_constant_ \
{ \
static char const str[]; \
static Size const length = COUNT_OF( value ) - 1; \
}; \
\
template< class Type > \
char const name##_constant_< Type >::str[] = value; \
\
template< class Type > \
Size const name##_constant_< Type >::length; \
\
typedef name##_constant_<void> name;
DEF_STRING( a, "Argh, MSVC!" )
DEF_STRING( b, "Blah blah" )
DEF_STRING( c, "Currently there's no 'inline' for data in C++." )
#include <iostream>
template< char const* s >
void foo() { std::cout << "foo() says: " << s << std::endl; }
int main()
{
using namespace std;
int const x[a::length] = {}; // Showing off compile time constant.
foo<a::str>(); // Showing off external linkage.
cout << a::length << " characters: \"" << a::str << "\"." << endl;
}
Cheers & hth.,
Your desired features are contradictory.
Length at compile time
Defined in header file
Single copy across compilation units
To get (1) and (2), you need to declare the variable as static or put it in an unnamed namespace. However, this will cause a definition in each compilation unit, which goes against (3).
To get (2) and (3), you need to declare the variable as extern, but then you won't get (1).
Now, if your linker is smart, it might optimize away the multiple copies, but I'm not sure if the standard allows it...
I recommend the const char FOO[] = "foo"; syntax declared in an unnamed namespace or as static if it need to be found in a specific namespace. If the string is very large, then I go for an extern.
This is how I see it. I wouldn't use any of those as it is. First, I'm inclined by #2, but, take into account that you have to declare the variable as extern in the .h, and select some .cpp to actually store the string:
// .h
extern const char*const STR;
// .cpp
const char*const STR = "abc";
The only drawback, not having the length at run-time, doesn't seem to me a real reason to move to other option. If you have several strings, you can always have a set of integer constants (or #defines) to specify each string's length, such as STR_LEN. If you have a lot of them, you won't write them at hand anyway, and you can then generate automatically the ..._LEN constants at the same time.
I think you took the wrong idea away from your previous question.
Strings tend to be sparse and not good for lookup, use numbers instead.
You still don't seem to get the difference between declaring in a .h and defining the storage in a .cpp thus avoiding multiple copies. Even if you had multiple copies (with different constant names) you would still have the issue you mentioned from your previous question.
has one fatal flaw. I cannot have static module level code that uses these strings since they might not have been constructed yet
The only way to avoid this is to bring the constants into the same scope with what you currently have at static module level.
Put all the related stuff in a class!
This is just Alf's answer macro'd:
#include <iostream>
#define string_constant(pName, pLiteral) \
template <typename = void> \
struct pName##_detail \
{ \
static const char value[]; \
}; \
\
template <typename T> \
const char pName##_detail<T>::value[] = pLiteral; \
\
typedef pName##_detail<> pName
string_constant(my_constant, "this is a literal");
int main()
{
std::cout << my_constant::value << std::endl;
std::cout << sizeof my_constant::value << std::endl;
}
codepad. Doesn't seem to work in VS2010. :/
I want to print out a function pointer using cout, and found it did not work.
But it worked after I converting the function pointer to (void *), so does printf with %p, such as
#include <iostream>
using namespace std;
int foo() {return 0;}
int main()
{
int (*pf)();
pf = foo;
cout << "cout << pf is " << pf << endl;
cout << "cout << (void *)pf is " << (void *)pf << endl;
printf("printf(\"%%p\", pf) is %p\n", pf);
return 0;
}
I compiled it with g++ and got results like this:
cout << pf is 1
cout << (void *)pf is 0x100000b0c
printf("%p", pf) is 0x100000b0c
So what does cout do with type int (*)()? I was told that the function pointer is treated as bool, is it true?
And what does cout do with type (void *)?
Thanks in advance.
EDIT: Anyhow, we can observe the content of a function pointer by converting it into (void *) and print it out using cout.
But it does not work for member function pointers and the compiler complains about the illegal conversion. I know that member function pointers is rather a complicated structure other than simple pointers, but how can we observe the content of a member function pointers?
There actually is an overload of the << operator that looks something like:
ostream & operator <<( ostream &, const void * );
which does what you expect - outputs in hex. There can be no such standard library overload for function pointers, because there are infinite number of types of them. So the pointer gets converted to another type, which in this case seems to be a bool - I can't offhand remember the rules for this.
Edit: The C++ Standard specifies:
4.12 Boolean conversions
1 An rvalue of arithmetic,
enumeration, pointer, or pointer to
member type can be converted to an
rvalue of type bool.
This is the only conversion specified for function pointers.
Regarding your edit, you can print out contents of anything by accessing it via unsigned char pointer. An example for pointers to member functions:
#include <iostream>
#include <iomanip>
struct foo { virtual void bar(){} };
struct foo2 { };
struct foo3 : foo2, foo { virtual void bar(){} };
int main()
{
void (foo3::*p)() = &foo::bar;
unsigned char const * first = reinterpret_cast<unsigned char *>(&p);
unsigned char const * last = reinterpret_cast<unsigned char *>(&p + 1);
for (; first != last; ++first)
{
std::cout << std::hex << std::setw(2) << std::setfill('0')
<< (int)*first << ' ';
}
std::cout << std::endl;
}
You can think of a function pointer as being the address of the first instruction in that function's machine code. Any pointer can be treated as a bool: 0 is false and everything else is true. As you observed, when cast to void * and given as an argument to the stream insertion operator (<<), the address is printed. (Viewed strictly, casting a pointer-to-function to void * is undefined.)
Without the cast, the story is a little complex. For matching overloaded functions ("overload resolution"), a C++ compiler gathers a set of candidate functions and from these candidates selects the "best viable" one, using implicit conversions if necessary. The wrinkle is the matching rules form a partial order, so multiple best-viable matches cause an ambiguity error.
In order of preference, the standard conversions (and of course there also user-defined and ellipsis conversions, not detailed) are
exact match (i.e., no conversion necessary)
promotion (e.g., int to float)
other conversions
The last category includes boolean conversions, and any pointer type may be converted to bool: 0 (or NULL) is false and everything else is true. The latter shows up as 1 when passed to the stream insertion operator.
To get 0 instead, change your initialization to
pf = 0;
Remember that initializing a pointer with a zero-valued constant expression yields the null pointer.
In C++11 one could modify this behavior by defining a variadic template overload of operator<< (whether that is recommendable or not is another topic):
#include<iostream>
namespace function_display{
template<class Ret, class... Args>
std::ostream& operator <<(std::ostream& os, Ret(*p)(Args...) ){ // star * is optional
return os << "funptr " << (void*)p;
}
}
// example code:
void fun_void_void(){};
void fun_void_double(double d){};
double fun_double_double(double d){return d;}
int main(){
using namespace function_display;
// ampersands & are optional
std::cout << "1. " << &fun_void_void << std::endl; // prints "1. funptr 0x40cb58"
std::cout << "2. " << &fun_void_double << std::endl; // prints "2. funptr 0x40cb5e"
std::cout << "3. " << &fun_double_double << std::endl; // prints "3. funptr 0x40cb69"
}
Casting pointers to (void*) to print them to cout is the right thing (TM) to do in C++ if you want to see their values.
Regarding your specific question,
how can we observe the content of a
member function pointers?
The answer is, other than converting them to bool to express that it points to something or it doesn't, you can't 'observer' member function pointers. At least not in a compliant way. The reason is because the standard explicitly disallows this:
4.12 footnote 57:
57) The rule for conversion of
pointers to members (from pointer to
member of base to pointer to member of
derived) appears inverted compared to
the rule for pointers to objects (from
pointer to derived to pointer to base)
(4.10, clause 10). This inversion is
necessary to ensure type safety. Note
that a pointer to member is not a
pointer to object or a pointer to
function and the rules for conversions
of such pointers do not apply to
pointers to members. In particular, a
pointer to member cannot be converted
to a void*.
For example, here is sample code:
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
class Gizmo
{
public:
void DoTheThing()
{
return;
};
private:
int foo_;
};
int main()
{
void(Gizmo::*fn)(void) = &Gizmo::DoTheThing;
Gizmo g;
(g.*fn)(); // once you have the function pointer, you can call the function this way
bool b = fn;
// void* v = (void*)fn; // standard explicitly disallows this conversion
cout << hex << fn;
return 0;
}
I note that my debugger (MSVC9) is able to tell me the actual physical address of the member function at runtime, so I know there must be some way to actually get that address. But I'm sure it is non-conformant, non-portable and probably involves machine code. If I were to go down that road, I would start by taking the address of the function pointer (eg &fn), casting that to void*, and go from there. This would also require you know the size of pointers (different on different platforms).
But I would ask, so long as you can convert the member-function pointer to bool and evaluate the existance of the pointer, why in real code would you need the address?
Presumably the answer to the last question is "so I can determine if one function pointer points to the same function as another." Fair enough. You can compare function pointers for equality:
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
class Gizmo
{
public:
void DoTheThing()
{
return;
};
**void DoTheOtherThing()
{
return;
};**
private:
int foo_;
};
int main()
{
void(Gizmo::*fn)(void) = &Gizmo::DoTheThing;
Gizmo g;
(g.*fn)(); // once you have the function pointer, you can call the function this way
bool b = fn;
// void* v = (void*)fn; // standard explicitly disallows this conversion
cout << hex << fn;
**void(Gizmo::*fnOther)(void) = &Gizmo::DoTheOtherThing;
bool same = fnOther == fn;
bool sameIsSame = fn == fn;**
return 0;
}
maybe (in one time I stay intersecting about the address of function)
one of decision )))
#include <iostream>
#include <stdlib.h>
void alexf();
int main()
{
int int_output;
printf("printf(\"%%p\", pf) is %p\n", alexf);
asm( "movl %[input], %%eax\n"
"movl %%eax, %[output]\n"
: [output] "+m" (int_output)
: [input] "r" (&alexf)
: "eax", "ebx"
);
std::cout<<"" <<std::hex<<int_output <<""<<std::endl;
return 0;
}
void alexf() { }
passing the pointer to function (&alexf) or other pointer using & use constraint r. Let gcc to use register for input argument)).
In C/C++, how do I determine the size of the member variable to a structure without needing to define a dummy variable of that structure type? Here's an example of how to do it wrong, but shows the intent:
typedef struct myStruct {
int x[10];
int y;
} myStruct_t;
const size_t sizeof_MyStruct_x = sizeof(myStruct_t.x); // error
For reference, this should be how to find the size of 'x' if you first define a dummy variable:
myStruct_t dummyStructVar;
const size_t sizeof_MyStruct_x = sizeof(dummyStructVar.x);
However, I'm hoping to avoid having to create a dummy variable just to get the size of 'x'. I think there's a clever way to recast 0 as a myStruct_t to help find the size of member variable 'x', but it's been long enough that I've forgotten the details, and can't seem to get a good Google search on this. Do you know?
Thanks!
In C++ (which is what the tags say), your "dummy variable" code can be replaced with:
sizeof myStruct_t().x;
No myStruct_t object will be created: the compiler only works out the static type of sizeof's operand, it doesn't execute the expression.
This works in C, and in C++ is better because it also works for classes without an accessible no-args constructor:
sizeof ((myStruct_t *)0)->x
I'm using following macro:
#include <iostream>
#define DIM_FIELD(struct_type, field) (sizeof( ((struct_type*)0)->field ))
int main()
{
struct ABC
{
int a;
char b;
double c;
};
std::cout << "ABC::a=" << DIM_FIELD(ABC, a)
<< " ABC::c=" << DIM_FIELD(ABC, c) << std::endl;
return 0;
}
Trick is treating 0 as pointer to your struct. This is resolved at compile time so it safe.
You can easily do
sizeof(myStruct().x)
As sizeof parameter is never executed, you'll not really create that object.
Any of these should work:
sizeof(myStruct_t().x;);
or
myStruct_t *tempPtr = NULL;
sizeof(tempPtr->x)
or
sizeof(((myStruct_t *)NULL)->x);
Because sizeof is evaluated at compile-time, not run-time, you won't have a problem dereferencing a NULL pointer.
In C++11, this can be done with sizeof(myStruct_t::x). C++11 also adds std::declval, which can be used for this (among other things):
#include <utility>
typedef struct myStruct {
int x[10];
int y;
} myStruct_t;
const std::size_t sizeof_MyStruct_x_normal = sizeof(myStruct_t::x);
const std::size_t sizeof_MyStruct_x_declval = sizeof(std::declval<myStruct_t>().x);
From my utility macros header:
#define FIELD_SIZE(type, field) (sizeof(((type *)0)->field))
invoked like so:
FIELD_SIZE(myStruct_t, x);