简体   繁体   中英

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?

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 + ...);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM