How can we ensure using concepts that both return type as well as argument types of variadic template is same?

Viewed 101

In the below code snippet I had used variadic template findSum function and in that I ensured that argument types of that function is same using concepts but can someone suggest that how can I also ensure that return type of that function also matches with that of argument types.

#include <iostream>
#include <concepts>
template<typename F,typename... R>
struct FirstVariadicType
{
    using Type = F;
};

template<typename... Ts>
requires requires(Ts... args){
std::conjunction_v<std::is_same<typename FirstVariadicType<Ts...>::Type, Ts>...>;
}
auto findSum(Ts... args)
{
     return (... + args);
}
int main()
{
    std::cout<<"sum of 2 and 3 is "<<findSum(2,3)<<std::endl;
    return 0;
}
2 Answers

You can do it with std::same_as, the concept equivalent of std::is_same. Simply use the concept in the arguments and the return type:

template<typename T>
auto f(T a, std::same_as<T> auto... b) -> std::same_as<T> auto {

}

Or using the terse syntax all the way:

auto f(auto a, std::same_as<decltype(a)> auto... b) -> std::same_as<decltype(a)> auto {

}

Or none of it:

template<typename T, std::same_as<T>... Rest>
auto f(T a, Rest... b) -> std::same_as<T> auto {

}

You can always take the type of your return expression

decltype((... + args))

And constrain it as you wish

std::is_same<decltype((... + args)), typename FirstVariadicType<Ts...>::Type>
Related