簡體   English   中英

推導函數指針類型的C ++

[英]c++ deducing a function pointer type

是否可以從函數參數推斷出非類型 函數指針類型模板參數(函數指針)

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

要調用此函數,我必須顯式聲明函數模板參數:

test<somefunc>(somefunc);

我知道我也可以這樣:

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

test<somefunc>();

但是我只是想知道是否可以這樣做:

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

test(somefunc);

是否可以這樣聲明,使編譯器(GCC 4.7)從函數參數中得出?

在此先感謝您,我真的很想知道如何執行此操作。 -布萊恩

是否可以從函數自變量推導出非類型模板自變量(函數指針)?

否。函數參數是運行時實體,模板參數是編譯時實體。 要推論,必須在運行時推論這樣的模板參數,這是不可能的。

Bryan,這似乎是底層C和C ++的怪異混合。 你為什么需要那個? 為什么不使用函子?

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

我這可能會做你想要的:

聲明一個沒有函數類型的基本模板:

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

專攻函數類型(主要是參數數量):

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

聲明一些具有不同簽名的測試功能:

void myfn0() { printf("hi 0\n"); }
void myfn1(int x) { printf("hi 1:%i\n",x); }
void myfnD(float y) { printf("hi D %f\n",y); }

現在執行它們:

int main(int,char**) {
   test(myfn0);
   test(myfn1);
   test(myfnD);
   return 0;
}

結果:

hi 0
hi 1:1
function signature not supported

這是您要找的東西嗎?

#include <iostream>

typedef void (*fptr)();

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM