关于模板:C ++推导函数指针类型

c++ deducing a function pointer type

是否可以从函数自变量推断出非类型函数指针类型模板自变量(函数指针)

1
2
template <void(*fptr)()>
  void test(void(*fp)()) { fp(); }

要调用此函数,我必须显式声明函数模板参数:

1
test<somefunc>(somefunc);

我知道我也可以这样:

1
2
3
4
template <void(*fptr)()>
  void test() { fp(); }

test<somefunc>();

但是我只是想知道是否可以这样做:

1
2
3
4
template <void(*fptr)()>
  void test() { fp(); }

test(somefunc);

是否可以这样声明,使编译器(GCC 4.7)从函数参数中得出?

在此先感谢您,我真的很想知道如何执行此操作。
-布莱恩


Is it possible to deduce a non-type template argument (function pointer) from a function argument?

否。函数参数是运行时实体,模板参数是编译时实体。 要推论,必须在运行时推论这样的模板参数,这是不可能的。


我这可能会做你想要的:

声明一个没有函数类型的基本模板:

1
2
template <typename T> void test(T fp) { printf("function signature not supported
"
); }

专攻函数类型(主要是参数数量):

1
2
3
4
typedef void(fptr0)();
template <> void test(fptr0 fp) { fp(); }
typedef void(fptr1)(int);
template <> void test(fptr1 fp) { fp(1); }

声明一些具有不同签名的测试功能:

1
2
3
4
5
6
void myfn0() { printf("hi 0
"
); }
void myfn1(int x) { printf("hi 1:%i
"
,x); }
void myfnD(float y) { printf("hi D %f
"
,y); }

现在执行它们:

1
2
3
4
5
6
int main(int,char**) {
   test(myfn0);
   test(myfn1);
   test(myfnD);
   return 0;
}

结果:

1
2
3
hi 0
hi 1:1
function signature not supported


Bryan,这似乎是底层C和C ++的怪异混合。 你为什么需要那个? 为什么不使用函子?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct clean
{
    void operator() ()
    {
        // do something here        
    }
};

template <typename FuncType> void call_func(FuncType func)
{
    func();
}

// here is how to pass 'clean' to be called
call_func(clean());

有关函子的更多信息,例如,在这里:http://www.cprogramming.com/tutorial/functors-function-objects-in-c++.html


这是您要找的东西吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

typedef void (*fptr)();

void f() {
    std::cout <<"hello, world
"
;
}

template <class fptr> void g(fptr fp) {
    fp();
}

int main() {
    g(f);
    return 0;
}