重载函数是完全不同的几个函数,有不同的函数地址,当我们调用函数时,编译器根据实参确定要调用哪一个重载函数。有时候我们需要不调用函数的情况下获取某个重载函数的地址(比如将重载函数作为接口导出),该怎么做呢?
除了函数调用以外,以下7种语境下也会让编译器对重载函数作出选择,我们可以通过指定函数指针类型获取重载函数地址。
#include "stdafx.h"
#include <cstdio>
#include <iostream>
int func(int value)
{
return value;
}
int func(double value)
{
return value;
}
void printFuncAddress(int(&f1)(int), int(*f2)(double))
{
printf("f1:%08x,f2:%08x\n", f1, f2);
}
struct PrintFuncStruct{
void operator<<(int(*f)(double))
{
printf("func:%08x\n", f);
}
};
typedef int(*func1)(int);
func1 getFunc()
{
return func;
}
template< int(*F)(int) >
struct Templ {};
int main()
{
//初始化时选择重载函数
int(*myFunc1)(int value) = &func;//选择int func(int value)
//函数名称前加不加取地址符结果都一样
int(*myFunc2)(double value) = func;//选择int func(double value)
printf("myFunc1:%08x,myFunc2:%08x\n", myFunc1, myFunc2);
//赋值时选择重载函数
myFunc1 = &func;//选择int func(int value)
printf("myFunc1:%08x,myFunc2:%08x\n", myFunc1, myFunc2);
//作为函数实参
//第一参数选择int func(int value)
//第二参数选择int func(double value)
printFuncAddress(func,func);
//自定义运算符
//选择int func(double value)
PrintFuncStruct printFuncStruct;
printFuncStruct << func;
//作为返回值
//选择int func(int value)
printf("func:%08x\n", getFunc());
//类型转换
//选择int func(int value)
auto p = static_cast<int(*)(int)>(func);
printf("func:%08x\n", p);
//模板实参
//选择int func(int value)
Templ<func> t;
system("pause");
return 0;
}
myFunc1:0137ff71,myFunc2:0137ff67
myFunc1:0137ff71,myFunc2:0137ff67
f1:0137ff71,f2:0137ff67
func:0137ff67
func:0137ff71
func:0137ff71