我有一个对我很有效的功能:
template <typename __container, typename __callback = std::function <
void (typename __container::value_type, typename __container::value_type)>
>
int reduce(__container &&container, __callback &&callback)
{
auto current = container.begin();
for (auto value : container)
*current = callback(*current, value);
return *current;
};
int result = functional::reduce(vector, [](const int current, const int next) -> int {
return current + next;
});
std::cout << result; // 10
现在,我要统一一个:
template <typename __container, typename __callback = std::function <
void (typename __container::value_type, typename __container::value_type)>
>
auto reduce(__container &&container, __callback &&callback) ->
decltype(__container::value_type);
但是我收到以下错误:
reduce.cpp:61:9: error: no matching function for call to 'reduce'
int i = reduce(vector, [](const int current, const int next) -> int {
^~~~~~~~~~~~~~~~~~
reduce.hpp:69:7: note: candidate template ignored: substitution failure [with __container = std::__1::list<int, std::__1::allocator<int>> &, __callback = <lambda at
nott.cpp:61:36>]
auto reduce(__container &&container, __callback &&callback) -> decltype(__container::value_type)
^
1 error generated.
make: *** [build] Error 1
如何设置通用返回类型?
更新:
template <typename __container, typename __callback>
auto reducef(const __container& input, __callback callback) ->
decltype(callback(std::declval<typename __container::value_type>(), std::declval<typename __container::value_type>()))
{
decltype(
callback(
std::declval<typename __container::value_type>(),
std::declval<typename __container::value_type>()
)
) result{};
return std::accumulate(input.begin(), input.end(), result, callback);
};