std::function<R(Args...)>::target
來自 cppreference.com
< cpp | utility | functional | function
template< class T > T* target() noexcept; |
(1) | (C++11 起) |
template< class T > const T* target() const noexcept; |
(2) | (C++11 起) |
返回指向儲存的可呼叫函式目標的指標。
目錄 |
[編輯] 引數
(無)
[編輯] 返回值
如果 target_type() == typeid(T),則返回指向儲存函式的指標,否則返回空指標。
[編輯] 示例
執行此程式碼
#include <functional> #include <iostream> int f(int, int) { return 1; } int g(int, int) { return 2; } void test(std::function<int(int, int)> const& arg) { std::cout << "test function: "; if (arg.target<std::plus<int>>()) std::cout << "it is plus\n"; if (arg.target<std::minus<int>>()) std::cout << "it is minus\n"; int (*const* ptr)(int, int) = arg.target<int(*)(int, int)>(); if (ptr && *ptr == f) std::cout << "it is the function f\n"; if (ptr && *ptr == g) std::cout << "it is the function g\n"; } int main() { test(std::function<int(int, int)>(std::plus<int>())); test(std::function<int(int, int)>(std::minus<int>())); test(std::function<int(int, int)>(f)); test(std::function<int(int, int)>(g)); }
輸出
test function: it is plus test function: it is minus test function: it is the function f test function: it is the function g
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 2591 | C++11 | 如果 T 不是 Callable,則行為未定義 |
行為已定義(總是返回 nullptr ) |
[編輯] 參閱
獲取儲存目標的 typeid (public member function) |