![](/img/trans.png)
[英]Trouble passing a template function as an argument to another function in C++
[英]Passing a function template as a function argument in C++
假設我有一個模板 function 以 integer 作為模板參數,如下所示:
template <int i> void f(int x) {...}
現在我想寫另一個 function 以 function f
作為參數。 但是我不知道如何實現這一點。 例如,考慮以下錯誤代碼(無法編譯):
template <template <int> typename T> void g(T fun, int i, int x) {
if (i == 0) fun<0>(x);
else if (i == 1) fun<1>(x);
//...
}
我搜索了谷歌,但似乎所有相關問題都是通過標准 function 作為模板參數,但這里不是這種情況。 希望任何人都可以幫助我。 非常感謝!
您可以使用可調用的 class 來模擬它:
template <int i>
struct f {
void operator()(int x) {
// ...
}
};
template <template <int> typename T>
void g(int i, int x) {
if (i == 0)
T<0>{}(x);
else if (i == 1)
T<1>{}(x);
//...
}
int main() {
g<f>(10, 12);
}
也可以對命名的 static 方法執行相同的操作。 但我建議你將模板參數設為常規參數,這樣你就不需要這樣的東西了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.