C++获取重载函数的地址

重载函数是完全不同的几个函数,有不同的函数地址,当我们调用函数时,编译器根据实参确定要调用哪一个重载函数。有时候我们需要不调用函数的情况下获取某个重载函数的地址(比如将重载函数作为接口导出),该怎么做呢?

除了函数调用以外,以下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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值