Reputation: 11
I am writing a template function which returns the difference of consecutive elements of a vector using std::minus
.
At present I have the following code:
template <typename T>
auto diffs(std::vector<T> &nums)
{
typedef decltype(std::minus<T>()) diffType;
std::vector<diffType> differences;
differences.reserve(nums.size() - 1);
auto test = std::back_inserter<std::vector<decltype (std::minus<T>())>>;
std::transform(++begin(nums), end(nums), begin(nums), std::back_inserter(differences), std::minus<T>());
return differences;
}
and am calling it using
void test()
{
auto values = std::vector<int>{ 1,2,4,6,89,1456 };
auto differences = diffs(values);
}
When I compile this I get:
binary '=': no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)
How do I declare my typedef
so that it works properly with my back_inserter
?
Upvotes: 1
Views: 75
Reputation: 303127
This:
decltype(std::minus<T>())
Is asking for the type of default constructing a minus<T>
, which is just minus<T>
. What you'd wanted is what happens when you invoke it:
decltype(std::minus<T>()(nums[0], nums[0]))
Or you could use a type trait instead:
std::invoke_result_t<std::minus<T>, T const&, T const&>
Upvotes: 5