简体   繁体   中英

Determining the Return Type of a Template Function

Given that I have a return type which is determined by a template argument, like so:

template <typename T>
conditional_t<is_same_v<T, int>, int, char> foo(const T&);

I thought that I could use decltype(foo<float>) to get this type but it doesn't seem to be working.

I don't have so I cannot use invoke_result_t .

I thought that I could use decltype(foo<float>) to get this type but it doesn't seem to be working.

The expression foo<float> refers to the function, so the decltype will be related with the type of the template function (ie, char (const float&) ).


What you are looking for is:

decltype(foo(std::declval<float>()))

That is, the expression returned by function foo when a float is given as input.

Of course, you can substitute float with any type in order to obtain the different results of the template function.


Example Code:

#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>) will give you a function type, something like char (float const&) . To get the return type you can use

using R = decltype(foo(std::declval<T>()));   // T = float

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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