如何创建与给定函数具有相同类型的变量?

Fre*_*abe 8 c++ templates

我有像C++这样的函数

int f( const std::string &s, double d );
Run Code Online (Sandbox Code Playgroud)

现在我想创建一个包含指针的变量f.这个变量应该有正确的类型(int (*)( const std::string &, double )- 但我不想明确地写出那种类型.我想推断它,f以便我不重复类型签名.最后,我希望能够写下以下内容:

TypeOf<f>::Result x = f;
Run Code Online (Sandbox Code Playgroud)

为了实现这一点,我尝试做这样的事情:

// 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;
Run Code Online (Sandbox Code Playgroud)

我希望也许函数的返回类型(deduceType在这种情况下)可以用作模板参数但是唉 - 似乎你不能这样做.

有人知道怎么做这个吗?我正在寻找一个C++ 03解决方案.

Tam*_*lei 10

C++ 0x添加了decltype,它可以满足您的需求(如果我理解正确的话).

另一个选项可能是Boost :: Typeof,它旨在提供相同的功能,直到所有编译器都支持decltype.