Template identifier vs decltype in the template function parameter

What do you think is the best?

template <typename T> void func(T x,T y) {}

or

template <typename T> void func(T x,decltype(x) y) {}

IMHO, the second form seems preferable because the relationship between types x and y is explicit and, at least when renaming the template identifier, things seem less error prone.

EDIT

The second form allows you to call a function with a subtype of one use for the first parameter, while the first form requires the same types. This argument seems a little better than the previous one.

+4
source share
2 answers

They are semantically different, so it depends on what you want to achieve. The second is more stringent than the first. Consider:

template <typename T> void func1(T x, decltype(x) y) {}
template <typename T> void func2(T x, T y) {}

func1(2., 4); // converts 4 to double
func2(2., 4); // fails to compile

SFINAE ( ), .

+3

. .

( ) , ( int) ( float): coliru.

+2

Source: https://habr.com/ru/post/1679714/


All Articles