如何使用typedef来简化作为函数指针的模板函数参数
How to use typedef to simplify tempate function argument that is a function pointer
我想通过使用typedef
来表示ptr
参数的类型来简化foo
。
#include <iostream>
template <unsigned N>
int foo (int (*ptr) (const char (*)[N])) {
char good[N] = "good";
return ptr(&good);
}
int bar (const char (*x)[5]) {
std::cout << *x << "n";
return 0;
}
int main ()
{
return foo(bar);
}
我想把foo()
写得更像这样:
template <unsigned N>
int foo (FUNCTION_TYPE *ptr) {
char good[N] = "good";
return ptr(&good);
}
我尝试使用像助手类这样的特征,但失败了。是否有一个合适的方法来创建 typedef
FUNCTION_TYPE
?
在c++ 11中,您可以通过使用using
关键字获得模板类型定义的大致等效。这仍然允许从参数推导出N
:
template <unsigned N>
using fooP = int (*) (const char (*)[N]);
template <unsigned N>
int foo (fooP<N> ptr) {
return ptr(0);
}
int bar(const char (*p)[2]) {
return 0;
}
int main() {
return foo(bar);
}
实际上你可以把它改成template
template<unsigned N, typename Func)
int foo(Func func){ return func("good"); }
int bar(const std::string& str){ return str == "good"; }
int main(){ const int r = foo(bar); }
这样不仅可以不局限于传递常规函数还可以传递函子
所以你的基本问题是依赖类型不能在函数调用中推断。
假设您想要在消除这种混乱的同时推断出值N
,那么您需要的是从函数类型映射到值N
的能力。
template<typename Func>
struct get_N {};
template<unsigned int N>
struct get_N< int( const char(*)[N] ) > {
typedef std::integral_constant< unsigned int, N > type;
};
template<typename Func>
using getN = typename get_N<Func>::type;
一旦你有了这个,你可以在template
类型参数中使用它:
template <typename Func, typename Nt = getN<Func>>
int foo (Func* ptr) {
constexpr N = Nt::value;
return ptr(&"good");
}
,我们可以访问foo
中的N
,唯一可以匹配foo
的东西(除非一些花哨的脚法)是get_N
理解的东西(通过SFINAE)。
是的,你可以使用默认模板参数:
template <unsigned N, typename T = int (*) (const char (*)[N])>
int foo (T ptr);
这是一个编译的演示。
另一个选项是使用std::function
:
#include <functional>
#include <string>
int foo(std::function<int(std::string)>& ptr)
{
// ...
}
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针