开发者

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

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 =开发者_StackOverflow中文版 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.


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.


You could declare your variable like this:

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

Here FuncPtr IS your variable. and you can use it like: int result = FuncPtr(str, d);, provided FuncPtr is not NULL. For that you could do:

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


If you're stuck with 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.); 
}


Better use typedef. You may repeat typedef name instead of the whole function signature.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜