[英]How to pass non-static member function as template argument to another member function?
我想做這樣的事情:
struct S
{
void mf() {};
template <auto f>
void func()
{
f();
}
};
int main()
{
S x;
x.func<x.mf>();
}
但是,這些是錯誤:
error: no matching function for call to 'S::func<x.S::mf>()'`
note: candidate: 'template<auto f> void S::func()'
note: template argument deduction/substitution failed:
error: could not convert 'x.S::mf' from '<unresolved overloaded function type>' to 'void (S::*)()'
我不確定我是否理解我做錯了什么。
為什么x.mf
沒有解析,因為我已經實例化了x
? 我如何使這項工作?
通過指針調用成員函數可能非常棘手。
你想一個成員函數指針傳遞給S::mf
像這樣:
struct S
{
void mf () {std::cout << "called mf\n";};
template <auto f>
void func ()
{
(this->*f)();
}
};
int main()
{
S x;
x.func<&S::mf>();
}
x.mf
不是類型而是成員函數指針。 我們必須將它作為參數傳遞。
這是您修改后的示例(不確定您想要做什么)。
#include <iostream>
struct S
{
int i=123;
void mf () { std::cout << "i=" << i << '\n'; };
template <typename f>
void func (f fnct)
{
(this->*fnct)();
}
};
int main()
{
S x{456};
x.func(&S::mf);
}
為什么
x.mf
沒有解析,因為我已經實例化了x
?
因為它不是有效的語法。 在那里你需要通過 operator &
提到成員函數,這意味着你應該有
x.func<&S::mf>();
// ^^^^^^^^
這樣模板參數就會被推導出對應的成員函數指針。 那是void(S::*)()
。
我如何使這項工作?
第二個問題是,函數調用f()
應該是通過成員函數指針的調用。 這與正常的函數調用不同。
用實例調用成員函數指針的傳統方式是
(this->*f)();
但是,從c++17 開始,這是使用更通用的庫函數的更方便的方法,因此從<functional>
頭文件中std::invoke
。
這意味着您可以通過像這樣的成員函數指針進行更具可讀性的調用。
#include <functional> // std::invoke
template <auto f>
void func()
{
std::invoke(f, this);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.