[英]Determining the Return Type of a Template Function
鑒於我有一個由模板參數確定的返回類型,如下所示:
template <typename T>
conditional_t<is_same_v<T, int>, int, char> foo(const T&);
我認為我可以使用decltype(foo<float>)
來獲取此類型,但它似乎不起作用。
我沒有c ++ 17所以我不能使用invoke_result_t
。
我認為我可以使用
decltype(foo<float>)
來獲取此類型,但它似乎不起作用。
表達式foo<float>
指的是函數,因此decltype
將與模板函數的類型相關(即char (const float&)
)。
你在尋找的是:
decltype(foo(std::declval<float>()))
也就是說,當一個float
作為輸入給出時,函數foo
返回的表達式。
當然,您可以使用任何類型替換float
,以獲得模板函數的不同結果。
示例代碼:
#include <type_traits>
#include <utility>
// Your template function
template <typename T>
std::conditional_t<std::is_same_v<T, int>, int, char> foo(const T&);
void test() {
decltype(foo(std::declval<float>())) x; // x is char in this case
// We can test the type of x at compile time
static_assert(!std::is_same_v<decltype(x), int>, "error"); // x is not an int
static_assert(std::is_same_v<decltype(x), char>, "error"); // x is a char
}
decltype(foo<float>)
將為您提供一個函數類型,類似於char (float const&)
。 要獲得您可以使用的返回類型
using R = decltype(foo(std::declval<T>())); // T = float
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.