簡體   English   中英

C++:如何使用 std::invoke_result_t 獲取 class 成員 function 的返回類型?

[英]C++: How can one get return type of a class member function using std::invoke_result_t?

如何使用 C++ 中的 std::invoke_result_t 獲得 class 成員 function 的返回類型?

#include <type_traits>
#include <vector>

template <class T>
struct C
{
    auto Get(void) const { return std::vector<T>{1,2,3}; }
};

int main(void)
{
 // what should one put below to make x to have type std::vector<int> ?
 std::invoke_result_t<C<int>::Get, void> x;
 //                   ^^^^^^^^^^^^^^^^^
 return 0;
}

非常感謝您的幫助!

std::invoke_result_t適用於types ,但C<int>::Get不是類型。 它是一個非靜態成員 function。

C<int>::Get類型std::vector<int>(C<int>::)()C<int>的成員 function 返回std::vector<int>並且不接受任何參數。 該類型是您需要提供給std::invoke_result_t的類型。 或者更確切地說,指向它的指針,因為您不能傳遞原始成員 function 類型。

此外, std::invoke_result_t將第一個參數類型視為 object 的類型,當它處理指向成員函數的指針時,在該類型上調用成員 function。

因此你需要:

std::invoke_result_t<std::vector<int>(C<int>::*)(), C<int>>

或者,如果您不想寫出整個成員 function 類型:

std::invoke_result_t<decltype(&C<int>::Get), C<int>>

演示


旁注: void參數列表相當於 C++ 中的空參數列表。 沒有理由在 C++ 中明確指定void參數列表,除非您想與 C 代碼共享 function 聲明。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM