我想在我的模板引數串列中使用函式指標。我確實想念 B 的一些東西,即使我寫的是和int的全部主要內容。我有一個這樣的課程,不知道現在是哪一個導致錯誤。ABX.h
struct X
{
int fun(int a)
{
return a;
}
template<typename A, typename B>
A func(int x, B(*f)(int))
{
A i = 10;
return i f(x);
}
};
我喜歡用它main.cpp
int main()
{
X d;
std::cout << d.func<int, int>(10, &X::fun) << "\n";
return 0;
}
錯誤是No instance of func matches the argument list...
uj5u.com熱心網友回復:
問題是引數&X::fun是型別,而int (X::*)(int)引數f是型別int(*)(int)(當 B = int 時),并且沒有從前者到后者的隱式轉換,因此存在錯誤。
要解決此問題,您可以將引數更改為如下所示f的型別。B(X::*)(int)請注意,使用成員函式指標進行呼叫的語法與呼叫自由函式的語法不同。
使用 C 17,我們可以使用std::invoke.
struct X
{
int fun(int a)
{
return a;
}
template<typename A, typename B>
//------------------vvvv-------------->added this X:: here
A func(int x, B(X::*f)(int))
{
A i = 10;
//-----------------vvvvvvvvvv-------->this is the syntax to call using member function pointer
return i (this->*f)(x);
//return std::invoke(f, this, x); //use std::invoke with C 17
}
};
int main()
{
X d;
std::cout << d.func<int, int>(10, &X::fun) << "\n"; //works now
return 0;
}
作業演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/523352.html
標籤:C
