![](/img/trans.png)
[英]Return type of overloaded named non-member function with invoke_result
[英]invoke_result to obtain return type of template member function
如何獲取模板成員函數的結果類型?
以下最小示例說明了該問題。
#include <type_traits>
template <typename U>
struct A {
};
struct B {
template <typename F = int>
A<F> f() { return A<F>{}; }
using default_return_type = std::invoke_result_t<decltype(f)>;
};
int main()
{
B::default_return_type x{};
return 0;
}
看到它住在Coliru。
代碼不編譯,報錯:
main.cpp:11:63: 錯誤:decltype 無法解析重載函數的地址
11 | 使用 default_return_type = std::invoke_result_t;
在模板參數F
設置為默認值的情況下,獲取B::f
類型的正確語法是什么?
您可以像這樣獲得返回類型:
using default_return_type = decltype(std::declval<B>().f());
完整示例:
#include <type_traits>
#include <iostream>
template <typename U>
struct A {
};
struct B {
template <typename F = int>
A<F> f() { return A<F>{}; }
using default_return_type = decltype(std::declval<B>().f());
};
int main()
{
B::default_return_type x{};
std::cout << std::is_same< B::default_return_type, A<int>>::value;
}
PS:似乎 clang 和較舊的 gcc 版本對B
是不完整的類型並調用f
不滿意。 作為一種解決方法,將using
移出類應該會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.