我正在嘗試模擬以下std::function功能,但遇到以下錯誤
class Player
{
public:
void move_to(Point location);
};
std::function<void(Player&, Point)> fun = &Player::move_to;
Player hero;
fun(hero, point{ 2, 4 });
fp.cc:32:33: error: variable ‘fun<void(Player&, Point)> f’ has initializer but incomplete type
32 | fun<void(Player &, Point p)> f = &Player::move_to;
#include <iostream>
using namespace std;
template <typename T>
struct fun;
template <typename Ret, typename T, typename ...Args>
struct fun <Ret(*)(T&, Args...)>{
char *data;
using fptr = Ret(T::*)(Args...);
fun(fptr p) : data(p) {}
Ret operator()(T &t, Args... args) {
if (std::is_same_v<Ret, void>) {
(t.*((fptr)data))(args...);
}
return (t.*((fptr)data))(args...);
}
};
struct Point {
int x;
int y;
};
struct Player {
void move_to(Point p) {
cout << __PRETTY_FUNCTION__ << endl;
}
};
int main() {
fun<void(Player &, Point p)> f = &Player::move_to;
Point p{1,2};
Player pl;
// f(pl, p);
}
uj5u.com熱心網友回復:
您的代碼很接近,但有幾個小錯誤:
您只提供了
funfor的定義Ret(*)(T&, Args...),但fun<void(Player &, Point p)>與此模板不匹配。因此,我洗掉了(*)您的專業中并不真正需要的內容。函式指標不可轉換為/從
char *,因此我將型別更改為data,fptr使其與引數型別匹配。
螺栓鏈接
#include <iostream>
using namespace std;
template <typename T>
struct fun;
template <typename Ret, typename T, typename ...Args>
struct fun <Ret(T&, Args...)>{
using fptr = Ret(T::*)(Args...);
fptr data;
fun(fptr p) : data(p) {}
Ret operator()(T &t, Args... args) {
if (std::is_same_v<Ret, void>) {
(t.*((fptr)data))(args...);
}
return (t.*((fptr)data))(args...);
}
};
struct Point {
int x;
int y;
};
struct Player {
void move_to(Point p) {
cout << __PRETTY_FUNCTION__ << endl;
}
};
int main() {
fun<void(Player &, Point p)> f = &Player::move_to;
Point p{1,2};
Player pl;
f(pl, p);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/410783.html
標籤:
上一篇:OutputIterator與std::back_inserter和std::ostream_iterator有什么關系?
下一篇:關于靜態初始化訂單慘敗的問題
