如何制作模板参数
How to make template parameter
如何创建一个接受任何类型函数指针的元函数?在下面的代码中,如何去掉"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();
}
编译器支持应该很快就会出现。
相关文章:
- 如何制作一个将函数作为参数的类方法
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 如何制作可以接受任何类型的参数的 std::函数和 lambda
- 如何在其他类中使用参数化构造函数制作类的对象?
- 你能用参数制作函数向量吗?
- 如何使用非特异性类型制作向量参数
- 如何根据模板参数制作代码生成
- C++:是否可以制作多类型函数参数?
- 是否可以制作一个定时函数,该函数可以将函数作为参数调用,然后运行并计时
- 休息:当我尝试制作包含JSON参数的requst时发出问题
- 如何制作智能指针的可变参数函数?
- 如何制作一个函数模板,该模板接受带有可变参数的函子
- 默认情况下,如何制作功能指针参数NO-OP
- 使用此功能的CV合并参数制作功能模板
- 如何在野牛C 中制作全局参数
- 如何基于模板参数制作方法const
- 如何制作一个指向列表迭代器的指针,以作为参数传递到函数中
- 如何制作模板参数
- 使用可变参数模板制作类似元组的编译时"linked-list"
- "return-by-reference"或"pass-by-reference"参数何时与constexpr兼容?