确定选择了哪个过载 [英] Determining which overload was selected

查看:136
本文介绍了确定选择了哪个过载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一些任意复杂的重载函数:

Let's say I have some arbitrary complicated overloaded function:

template <class T> void foo(T&& );
template <class T> void foo(T* );
void foo(int );

我想知道,对于给定的表达式, foo()被调用。例如,给定一些宏 WHICH_OVERLOAD

I want to know, for a given expression, which foo() gets called. For example, given some macro WHICH_OVERLOAD:

using T = WHICH_OVERLOAD(foo, 0);       // T is void(*)(int);
using U = WHICH_OVERLOAD(foo, "hello"); // U is void(*)(const char*);
// etc.

我不知道我会在哪里使用这样的东西 - 我只是好奇,如果它的可能。

I don't know where I would use such a thing - I'm just curious if it's possible.

推荐答案

Barry,对不起,我的第一个答案的误解。一开始我以错误的方式理解了你的问题。 'T.C.'是对的,这是不可能的,除非在一些罕见的情况下,你的函数有不同的结果类型根据给定的参数。在这种情况下,你甚至可以得到函数的指针。

Barry, sorry for the misunderstanding in my first answer. In the beginning I understood your question in a wrong way. 'T.C.' is right, that it is not possible except in some rare cases when your functions have different result types depending on the given arguments. In such cases you can even get the pointers of the functions.

#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>

这篇关于确定选择了哪个过载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆