[英]Deducing a function pointer return type
我認為代碼會更好地說明我的需要:
template <typename F>
struct return_type
{
typedef ??? type;
};
以便:
return_type<int(*)()>::type -> int
return_type<void(*)(int,int)>::type -> void
我知道decltype
和result_of
但他們需要通過 arguments。 我想從單個模板參數中推斷出 function 指針的返回類型。 我不能將返回類型添加為參數,因為這正是我想在這里隱藏的內容......
我知道在 boost 中有一個解決方案,但我不能使用它,並且試圖從 boost 中挖掘它導致了一個驚人的失敗(正如它經常發生的那樣)。
歡迎C++11解答(只要VS2012支持)。
如果你可以使用可變參數模板(11月'12 CTP),這應該工作:
template <class F>
struct return_type;
template <class R, class... A>
struct return_type<R (*)(A...)>
{
typedef R type;
};
實例 。
如果您不能使用可變參數模板,則必須為0,1,2,...參數(手動或預處理器生成)提供特定的特化。
編輯
正如評論中所指出的,如果你想使用可變參數函數,你將不得不添加一個額外的部分特化(或者在無變量模板的情況下為每個參數計數添加一個):
template <class R, class... A>
struct return_type<R (*)(A..., ...)>
{
typedef R type;
};
自問這個問題以來已經有一段時間了。 對於 C++17,有一個有趣的選項。 但是,語法與最初要求的有點不同,但結果(類型)是相同的。
首先,我們需要一個助手 function。正如您在此處看到的,function 接受一個 function 指針並返回一個類型為 R 的 object。我們只需要一個 decltype 語句,因此這個 8834004065898 永遠不會被稱為足夠的前向聲明, .
template<typename R, typename... ARGS>
static R return_type(R (*)(ARGS...)); // forward declaration only for decltype
訣竅是提供 function 指針作為模板自動參數,它被轉發到 decltype 語句:
template<auto FUNCTION_POINTER>
using ReturnType = decltype(return_type(FUNCTION_POINTER));
現在很容易得到返回類型:
#include <iostream>
#include <type_traits>
template<typename R, typename... ARGS>
static R return_type(R (*)(ARGS...)); // forward declaration only for decltype
template<auto FUNCTION_POINTER>
using ReturnType = decltype(return_type(FUNCTION_POINTER));
int func1(char c, int i, long l); // also here only forward declarations needed
void func2(unsigned u, float f);
double func3(bool b);
int main()
{
std::cout << std::is_same_v<int, ReturnType<func1>> << std::endl;
std::cout << std::is_same_v<void, ReturnType<func2>> << std::endl;
std::cout << std::is_same_v<double, ReturnType<func3>> << std::endl;
std::cout << std::is_same_v<void, ReturnType<func1>> << std::endl;
}
您可以在 Wandbox 中嘗試完整的示例: https://wandbox.org/permlink/5akL0MQDoDuJlQNY
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.