[英]Alias to a function template specialization
int f1(int a, int b) { return a+b; }
int f2(int a, int b) { return a*b; }
template <typename F> void foo(int i, int j)
{
// do some processing before
F(i,j);
// do some processing after
}
我想像這樣對foo的專業化做一個別名:
constexpr auto foo1 = &foo<f1>;
constexpr auto foo2 = &foo<f2>;
並像這樣調用函數: foo1(1,2);foo2(1,2);
有什么辦法可以在C ++中實現呢? 謝謝!
編輯: foo()不是f1的包裝,它是一個調用f1或f2的函數。 在通話之前和之后,我需要做一些額外的事情。 F是一個函子,我想要foo的專業化的“捷徑”。 上面的代碼是偽代碼。
注釋中有一些好的方法:std :: bind,使用lambda,將F
的實例傳遞到函數中,因此我將提供一種替代方法。
如果要傳遞給foo
的函數類型始終是int(int, int)
,那么您可以將template參數設為非類型template參數,然后使用其中一個函數實例化它:
int f1(int a, int b) { std::cout<<"f1\n"; return a+b; }
int f2(int a, int b) { std::cout<<"f2\n"; return a*b; }
template <int(*F)(int, int)>
void foo(int i, int j)
{
F(i,j);
}
然后這樣稱呼它:
int main()
{
constexpr auto foo1 = foo<f1>;
constexpr auto foo2 = foo<f2>;
foo1(1,2);
foo2(1,2);
}
輸出:
F1
F2
我們在這里做的技巧是使模板參數成為對函數的引用,雖然該函數很笨拙但合法AFAIK。
接受的答案應OP的要求而定。 為了補充這個答案:一種替代方法是讓int(int, int)
函數指針成為該函數的附加參數(在這種情況下,我們無需使用模板技術),然后使用std::bind
設置使用不同的默認大小寫函數。
#include <iostream>
#include <functional>
int f1(int a, int b) { return a+b; }
int f2(int a, int b) { return a*b; }
int f3(int a, int b) { return a-b; }
void foo(int i, int j, int (*f)(int, int)) {
// do some processing before
std::cout << f(i, j) << std::endl;
// do some processing after
}
int main()
{
const auto foo1 = std::bind(foo, std::placeholders::_1, std::placeholders::_2, &f1);
const auto foo2 = std::bind(foo, std::placeholders::_1, std::placeholders::_2, &f2);
foo1(5, 5); // 10
foo2(5, 5); // 25
foo(5, 5, &f3); // 0
return 0;
}
上面的一種變體可以允許使用函數包裝器( std::function
)將幫助函數存儲為值, foo1
由於某種原因,這些函數可能會超出調用者對象( foo1
, foo2
,...)的范圍。 )。
void foo(int i, int j, const std::function<int(int, int)> f) { /* ... */ }
// ...
const auto foo1 = std::bind(foo, std::placeholders::_1, std::placeholders::_2, f1);
const auto foo2 = std::bind(foo, std::placeholders::_1, std::placeholders::_2, f2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.