正如標題所說,在Request() 中沒有任何額外的引數,同時保持干凈。下面是一個例子:
struct CPerson
{
void Request();
}
void CPerson::Request()
{
// get index
/* EXAMPLES
serverinfo* info;
server.GetInfo(&info, index);
cout << info.username << "\n";
*/
}
CPerson person[64];
int main()
{
for (int i = 0; i < 64; i )
person[i].Request(); // i = current index
return 0;
}
編輯:固定標題
uj5u.com熱心網友回復:
在這種特定情況下,只要您可以保證CPerson只存盤在此陣列中,就可以使用std::distance()來獲取索引,因為它this恰好是陣列中的有效迭代器。
這實際上與執行 相同this - person,但標準庫實作可以(并且經常這樣做)在除錯版本中具有額外的安全網,而不會為發布版本帶來性能成本。
即使有額外的安全性,手動錯誤檢查以驗證作為其中this一部分的假設person仍然是一個好主意。為此,您需要使用std::less(而不是關系運算子),因為即使對于不在陣列內的指標,它也保證全域有效。
// C 11 and up.
#include <iterator>
#include <stdexcept>
struct CPerson
{
void Request();
};
CPerson person[64];
void CPerson::Request()
{
// possibly an assert() instead...
if(std::less<CPerson*>{}(this, std::begin(person)) ||
!std::less<CPerson*>{}(this, std::end(person))) {
throw std::out_of_range("not part of person");
}
std::size_t index = std::distance(std::begin(person), this);
}
在 C 20 中,你可以更通用,它可以person是任何連續的范圍,std::vector例如:
// C 20 and up.
#include <ranges>
#include <stdexcept>
#include <vector>
struct CPerson
{
std::size_t Index() const;
void Request();
};
CPerson person[64];
// Or possibly
// std::vector<CPerson> person;
std::size_t CPerson::Index() const
{
static_assert(std::ranges::contiguous_range<decltype(person)>);
const CPerson* person_b = std::to_address(std::ranges::begin(person));
const CPerson* person_e = std::to_address(std::ranges::end(person));
if(std::less{}(this, person_b) ||
!std::less{}(this, person_e)) {
throw std::out_of_range("not part of person");
}
return std::distance(person_b, this);
}
void CPerson::Request() {
auto i = Index();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/369784.html
