繁体   English   中英

确定模板函数的返回类型

[英]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>)来获取此类型,但它似乎不起作用。

我没有所以我不能使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM