Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a variable with the same type as a given function?

Tags:

c++

templates

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.

like image 256
Frerich Raabe Avatar asked May 11 '11 09:05

Frerich Raabe


People also ask

Can we create two variables same name?

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.

Can different variables have the same name?

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.

How many parameters can a function have?

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.


1 Answers

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.

like image 100
Tamás Szelei Avatar answered Sep 29 '22 13:09

Tamás Szelei