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 c++17 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 (i.e., 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
}