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

I have a C ++ function like

int f( const std::string &s, double d ); 

Now I would like to create a variable that contains a pointer to f . This variable must have the correct type ( int (*)( const std::string &, double ) - but I do not want to explicitly write out this type. I would like to draw a conclusion from f so that I do not repeat the type signature. In the end, I "I like to write something line by line:

 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 perhaps the return type of the function ( deduceType , in this case) could be used as an argument to the template, but, alas, it looks like you can't do this.

Does anyone know how to do this? I am looking for a C ++ 03 solution.

+8
c ++ templates
source share
4 answers

C ++ 0x added decltype , which does what you want (if I understood correctly).

Another option might be Boost :: Typeof , which is designed to provide the same function until decltype is supported by all compilers.

+9
source share

You can declare your variable as follows:

 int (*FuncPtr)(const std::string& s, double d); 

Here FuncPtr is your variable. and you can use it like: int result = FuncPtr(str, d); if FuncPtr is not NULL. To do this, you can:

 int result = 0; if (FuncPtr) { result = FuncPtr(str, doubleValue); } 
0
source share

If you are stuck in the current standard, use BOOST_TYPEOF - ala:

 #include <iostream> #include <boost/typeof/typeof.hpp> struct foo { int f( const std::string &s, double d ){ std::cout << "foo::f()" << std::endl; return 0;} }; int main(void) { BOOST_TYPEOF(&foo::f) x = &foo::f; foo f1; std::string s("he"); (f1.*x)(s, 0.); } 
0
source share

Better to use typedef. You can repeat the name of typedef rather than the whole signature of the function.

In most cases, typeof is not a good idea, even if you can do it.

 typedef int (*FuncType)( const std::string &s, double d ); 
0
source share

All Articles