假设我有一些任意复杂的重载函数:
template <class T> void foo(T&& );
template <class T> void foo(T* );
void foo(int );
我想知道,对于给定的表达式,which foo()
被调用。例如,给定一些宏 WHICH_OVERLOAD
:
using T = WHICH_OVERLOAD(foo, 0); // T is void(*)(int);
using U = WHICH_OVERLOAD(foo, "hello"); // U is void(*)(const char*);
// etc.
我不知道我会在哪里使用这样的东西 - 我只是好奇它是否可能。
最佳答案
巴里,很抱歉在我的第一个回答中造成了误解。一开始我以错误的方式理解你的问题。 'T.C.'是的,除非在极少数情况下,当您的函数根据给定的参数具有不同的结果类型时,这是不可能的。在这种情况下,您甚至可以获得函数的指针。
#include <string>
#include <vector>
#include <iostream>
//template <class T> T foo(T ) { std::cout << "template" << std::endl; return {}; };
std::string foo(std::string) { std::cout << "string" << std::endl; return {}; };
std::vector<int> foo(std::vector<int>) { std::cout << "vector<int>" << std::endl; return {}; };
char foo(char) { std::cout << "char" << std::endl; return {}; };
template<typename T>
struct Temp
{
using type = T (*) (T);
};
#define GET_OVERLOAD(func,param) static_cast<Temp<decltype(foo(param))>::type>(func);
int main(void)
{
auto fPtr1 = GET_OVERLOAD(foo, 0);
fPtr1({});
auto fPtr2 = GET_OVERLOAD(foo, std::string{"hello"});
fPtr2({});
auto fPtr3 = GET_OVERLOAD(foo, std::initializer_list<char>{});
fPtr3({});
auto fPtr4 = GET_OVERLOAD(foo, std::vector<int>{});
fPtr4({});
auto fPtr5 = GET_OVERLOAD(foo, std::initializer_list<int>{});
fPtr5({});
return 0;
}
输出是:
char
string
string
vector<int>
vector<int>
关于c++ - 确定选择了哪个重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35561453/