Hariom Singh
Hariom Singh

Reputation: 3632

Fold Expression template argument deduction/substitution failed

Trying to Learn fold expression .Getting error for argument deduction failed

#include<iostream>

template <typename T>
struct sum{
    T value;
    template <typename ... Ts>
    sum(Ts&&...values) : value{(values + ...)}{}//error here
};
int main()
{
    sum s(2,3,4);
}

Error

main.cpp: In function 'int main()':
main.cpp:11:16: error: class template argument deduction failed:
     sum s(2,3,4);
                ^
main.cpp:11:16: error: no matching function for call to 'sum(int, int, int)'
main.cpp:7:5: note: candidate: template<class T, class ... Ts> sum(Ts&& ...)-> sum<T>
     sum(Ts&&...values) : value{(values + ...)}{}
     ^~~
main.cpp:7:5: note:   template argument deduction/substitution failed:
main.cpp:11:16: note:   couldn't deduce template parameter 'T'
     sum s(2,3,4);

DEMO

How can I fix this error?

Upvotes: 3

Views: 181

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96791

It's not about fold expressions. The compiler is complaining because it has no way to deduce the typename T.

To solve that, you could provide a deduction guide after the class definiton, like so:

template <typename ...P> sum(P &&... p) -> sum<decltype((p + ...))>;

Alternatively, you could manually specify the argument: sum<int> s(2,3,4);


But I'd rather make sum a function. What's the point of making it a class anyway?

template <typename ...P> auto sum (P &&... p)
{
    return (p + ...);
}

Upvotes: 7

Related Questions