如何制作模板参数
How to make template parameter
如何创建接受任何类型函数指针的元函数?在下面的代码中,如何去掉 "decltype(&f)" ?
template <class FuncType, FuncType functionPointer>
void runFunc()
{
functionPointer();
}
runFunc<decltype(&f),f>();
我不想单独指定 f 的类型;信息已经存在于 f 中。我不想求助于定义来解决这个问题。
这基本上是应用于元编程的模板化函数类型习惯用法;我不想知道 f 的类型,但无论我输入什么,显然都允许我对其调用 operator()。
我尝试过的东西:
模板参数顺序不同;因为当你有一个函数时,后面的参数似乎是可以猜测的;不可能,因为那样你需要转发声明 FuncType,以便将其作为 functionPointer
的类型
将其转换为指定返回类型和参数并给出该类型的函数指针;无法实例化中间带有可变模板参数的模板;如下所示:
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 <auto functionPointer>
void runFunc() {
functionPointer();
}
编译器支持应该很快就会到来。
你可以使用这个:
template <typename FuncType>
void runFunc(FuncType functionPointer )
{
functionPointer();
}
runFunc(f);
如何创建接受任何类型函数指针的元函数?在下面的代码中,如何去掉 "decltype(&f)" ?
template <class FuncType, FuncType functionPointer>
void runFunc()
{
functionPointer();
}
runFunc<decltype(&f),f>();
我不想单独指定 f 的类型;信息已经存在于 f 中。我不想求助于定义来解决这个问题。 这基本上是应用于元编程的模板化函数类型习惯用法;我不想知道 f 的类型,但无论我输入什么,显然都允许我对其调用 operator()。
我尝试过的东西:
模板参数顺序不同;因为当你有一个函数时,后面的参数似乎是可以猜测的;不可能,因为那样你需要转发声明 FuncType,以便将其作为 functionPointer
的类型将其转换为指定返回类型和参数并给出该类型的函数指针;无法实例化中间带有可变模板参数的模板;如下所示:
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 <auto functionPointer>
void runFunc() {
functionPointer();
}
编译器支持应该很快就会到来。
你可以使用这个:
template <typename FuncType>
void runFunc(FuncType functionPointer )
{
functionPointer();
}
runFunc(f);