Is it legal to use function with no definition c++?

Viewed 139

I've seen some snippet of code from this page https://en.cppreference.com/w/cpp/types/result_of and have noticed this specific function template signature type:

template<class F, class... Args>
static auto call(F&& f, Args&&... args)
-> decltype(std::forward<F>(f)(std::forward<Args>(args)...));

Note: From the given implementation, there is no definition at all and only specifies its return type.

If this is possible, what are the possible applications that can be used for this?

1 Answers

Yes, this is allowed. decltype is an unevaluated context so the function isn't actually called, only it's return type is determined. Take std::declval for example. It is a function template declared by the standard and is only allowed to be used in an unevaluated expression as it may have no definition.

I like to call these types of function meta functions. You can use them like type traits, or as helpers to build types for template code. I used one in an answer the other day which was used to help convert a tuple of one type to another. It looked like

template <template <typename> typename Transformer, typename... Ts> 
auto transform_types(std::tuple<Ts...>) -> std::tuple<typename Transformer<Ts>::type...>;

and I used it to build a type like

template <template <typename> typename Transformer, typename Tuple>
using transform_types_t = decltype(transform_types<Transformer>(std::declval<Tuple>()));

Here is a link to that post if you want to see the full example: Transform the std::tuple types to another ones

Related