gpt4 book ai didi

c++ - 如何获得指向编译器选择的重载函数的函数指针?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:04:05 26 4
gpt4 key购买 nike

如何获得指向编译器在检查参数后选择的重载函数的函数指针?在这个例子中:

#include <iostream>

void MyFunction(float a){}
void MyFunction(int a){}

int main()
{
float a;

MyFunction(a);

void (*manualFunctionPointer)(float);
manualFunctionPointer(a);

// automaticFunctionPointer = ?
}

我已指定我想要一个函数指针,该函数指针指向接受 float 并返回 void 的函数。编译器当然可以自己解决这个问题,因为 MyFunction(a) 调用调用了正确的函数。有没有办法获取指向编译器选择的函数的函数指针?

最佳答案

#include <iostream>

void MyFunction(float a){std::cout << "float\n";}
void MyFunction(int a){std::cout << "int\n";}

template<typename Func, typename T>
void Do( Func f, T t )
{
f(t);
}
template<typename T>
void DoMyFunction( T t )
{
Do(static_cast<void(*)(T)>(MyFunction), t);
}
template<typename T>
void DoSomeFunction( T t, void(*func)(T) )
{
Do(func, t);
}
int main()
{
float a;

MyFunction(a);

void (*manualFunctionPointer)(float) = MyFunction;
manualFunctionPointer(a);

// Do(MyFunction, a); -- does not compile
Do(static_cast<void(*)(float)>(MyFunction), a);
DoMyFunction(a);
DoSomeFunction(a, MyFunction);
}

以上作品。我以 4 种不同的方式选择了 MyFunction。

如果您愿意做一些样例,并想解决“如果 a 是 char”问题,那么这可能会有所帮助:

// wrap the idea of calling MyFunction in a type:
struct MyFunctionFunctor {
template<typename T> static auto Do( T&& t )->decltype(MyFunction(std::forward(t))) {
return MyFunction(std::forward(t));
}
};
// Calling MyFunctionFunctor::Do( x ) will basically do static dispatch on all of
// the overloads of MyFunction

// wrap the idea of dispatching a variable to a functor:
template<typename T, typename Functor>
struct Dispatch {
static auto Do( T t )->decltype( Functor::Do( t ) )
{
return Functor::Do( t );
}
}

int main()
{
char a;
auto func_ptr = &Dispatch<decltype(a), MyFunctionFunctor>::Do;
func_ptr(a);
}

但是,如前所述,这需要我们将 MyFunction 包装起来,以便通过类型对其进行描述。我不知道有什么方法可以在没有样板的情况下执行此操作。

关于c++ - 如何获得指向编译器选择的重载函数的函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13632507/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com