I have a C++ function like
int f( const std::string &s, double d );
Now I'd like to create a variable which holds a pointer to f
. This variable should have the correct type (int (*)( const std::string &, double )
- but I don't want to write out that type explicitely. I'd like to deduce it from f
so that I don't repeat the type signature. Eventually, I'd like to be able to write something along the lines of:
TypeOf<f>::Result x = f;
To achieve this, I tried to do something like this:
// Never implemented, only used to deduce the return type into something which can be typedef'ed
template <typename T> T deduceType( T fn );
template <typename T>
struct TypeOf {
typedef T Result;
};
// ...
TypeOf<deduceType(f)>::Result x = f;
My hope was that maybe the return type of a function (deduceType
, in this case) could be used as a template argument but alas - it seems you can't do that.
Does anybody know how to do this? I'm looking for a C++03 solution.
Said in simple terms, if multiple variables in a program have the same name, then there are fixed guidelines that the compiler follows as to which variable to pick for the execution.
In a word, yes. Variable names only hold in the scope they're defined in, and you can use the same name in different scopes.
The main function can be defined with no parameters or with two parameters (for passing command-line arguments to a program when it begins executing). The two parameters are referred to here as argc and argv, though any names can be used because they are local to the function in which they are declared.
C++0x added decltype which does what you want (if I understood correctly).
Another option might be Boost::Typeof which is intended to provide the same functionality until decltype is supported in all compilers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With