Извлечение типа возврата из перегруженной функции

Я хочу извлечь обратный тип функции. Проблема в том, что есть другие функции с тем же именем, но и разной подписью, и я не могу получить C ++, чтобы выбрать соответствующую. Я знаю о STD :: Reals_of, но из нескольких попыток я пришел к выводу, что он также страдает от той же проблемы. Я слышал о решении, связанном с DECLTYPE, но я не знаю никаких особенностей.

На данный момент я использую шаблон MetaProgramming, чтобы извлечь тип возвращаемого типа из типа указателя функции, который работает нормально для ограниченного количества параметров (любое не ограниченное решение?), Учитывая, что извлечение типа указателя функции работает для однозначных Функции.

#include <iostream>

using namespace std;

//  ----

#define resultof(x)     typename ResultOf<typeof(x)>::Type  //  might need a & before x

template <class T>
class ResultOf
{
    public:
        typedef void Type;      //  might need to be T instead of void; see below
};

template <class R>
class ResultOf<R (*) ()>
{
    public:
        typedef R Type;
};

template <class R, class P>
class ResultOf<R (*) (P)>
{
    public:
        typedef R Type;
};

//  ----

class NoDefaultConstructor
{
    public:
        NoDefaultConstructor (int) {}
};


int f ();
int f ()
{
    cout << "f" << endl;
    return 1;
}

double f (int x);
double f (int x)
{
    cout << "f(int)" << endl;
    return x + 2.0;
}

bool f (NoDefaultConstructor);
bool f (NoDefaultConstructor)
{
    cout << "f(const NoDefaultConstructor)" << endl;
    return false;
}

int g ();
int g ()
{
    cout << "g" << endl;
    return 4;
}

int main (int argc, char* argv[])
{
    if(argc||argv){}

//  this works since there is no ambiguity. does not work without &
//  resultof(&g) x0 = 1;
//  cout << x0 << endl;

//  does not work since type of f is unknown due to ambiguity. same thing without &
//  resultof(&f) x1 = 1;
//  cout << x1 << endl;

//  does not work since typeof(f()) is int, not a member function pointer; we COULD use T instead of void in the unspecialized class template to make it work. same thing with &
//  resultof(f()) x2 = 1;
//  cout << x2 << endl;

//  does not work per above, and compiler thinks differently from a human about f(int); no idea how to make it correct
//  resultof(f(int)) x3 = 1;
//  cout << x3 << endl;

//  does not work per case 2
//  resultof(f(int())) x4 = 1;
//  cout << x4 << endl;

//  does not work per case 2, and due to the lack of a default constructor
//  resultof(f(NoDefaultConstructor())) x5 = 1;
//  cout << x5 << endl;

//  this works but it does not solve the problem, we need to extract return type from a particular function, not a function type
//  resultof(int(*)(int)) x6 = 1;
//  cout << x6 << endl;

}

Любая идея, какой функцией синтаксиса я отсутствую, и как это исправить, желательно с решением, которое работает простым способом, например, Результаты (F (INT)) ?

11
задан Frigo 31 August 2011 в 16:52
поделиться