0%

Deducing this and Function Pointer to Member Function in C++

看到一篇文章很有啟發,於是想記錄起來
傳統的Function Pointer to Member Function in C++的是這個樣子

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
class Test {
public:
void traditional() {
std::cout << "traditional: " << x << std::endl;
}
};
int main() {
Test t;
void (Test::*trad_ptr)() = &Test::traditional;
(t.*trad_ptr)();
}

有以下的缺點

  • 語法複雜
    • `void (ClassName::*ptr)(params)
  • 使用複雜
    • (obj.*ptr)(args)或是(obj->*ptr)(args) 
  • 無法將這個pointer轉成一般 function pointer
    而Deducing this就正好簡化了這個問題
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    class Test {
    public:
    void explicit_this(this Test& self) {
    std::cout << "Deducing this\n";
    }
    };

    int main() {
    Test t;

    t.explicit_this();

    void (*explicit_ptr)(Test&) = &Test::explicit_this;

    explicit_ptr(t);
    }
    由於他是一個member function,
  • 所以他可以透過t.explicit_this()直接呼叫
  • 他的function signature就變成了void (*)(Test&),可以直接賦值給function pointer或是std::function
  • 呼叫的方式直接購過explicit_ptr(t),比起上面的更加容易理解
    酸是Deducing this義想不到的好處之一