如何制作模板参数

How to make template parameter

本文关键字:参数 何制作      更新时间:2023-10-16

如何创建一个接受任何类型函数指针的元函数?在下面的代码中,如何去掉"decltype(&f)"?

template <class FuncType, FuncType functionPointer>
void runFunc()
{
    functionPointer();
}
runFunc<decltype(&f),f>();

我不想单独指定f的类型;信息已经在f中了。我不想用define来解决这个问题。这基本上是应用于元编程的模板化函数类型习惯用法;我不想知道f的类型,但无论我输入什么,显然都可以调用它的运算符()

我试过的东西:

模板参数的顺序不同;因为当你有一个函数时,后面的参数似乎是可以猜测的;不可能,因为您需要转发声明FuncType,以便将其作为函数指针的类型

切换它,以便指定returntype和参数,并给出该类型的函数指针;无法实例化中间有变量模板参数的模板;如下所示:

template <class ReturnType, class ... ArgTypes, ReturnType (*functionPointer)(ArgTypes...)>
void runFunc()
{
    functionPointer();
}
runFunc<void, int, f>(); // error; invalid template argument for 'ArgTypes', type expected

github上还有更多的上下文:https://github.com/TamaHobbit/FuncTest/blob/master/FuncTest/FuncTest.cpp

您可以使用这个:

template <typename FuncType>
void runFunc(FuncType functionPointer )
{
    functionPointer();
}
runFunc(f);

不幸的是,现在没有好的方法来做到这一点。

然而,标准委员会已经接受了一项使该代码有效的提案:

template <auto functionPointer>
void runFunc() {
  functionPointer();
}

编译器支持应该很快就会出现。