c++ - 确定选择了哪个重载

标签 c++ c++11 overload-resolution

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

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/

相关文章:

c++ - 涉及 vector (数组)的快速简单的约束规划

c++ - Type Alias 一个自定义类的对象

c# - C# 6 中方法重载解析的重大变化 - 解释?

c++ - 使用 fork() 的子和父 pid;

c++ - macOS - 读取其他应用程序库代码的一部分并将其反汇编以获取偏移量

C++ 无处引用

c++ - QListWidget 不允许图标大小大于 200

c++ - (shared_ptr+weak_ptr)兼容原始指针的设计

c++ - 了解方法重载规则

c# - 通用扩展方法解析失败