簡體   English   中英

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.

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