Вопрос

Disclaimer: I've seen this question and I'm precisely asking how decltype, suggested in the accepted answer, can be used for that.

Basically I try (a bit for fun, a bit for convenience, and a bit for learning purpose) to implement small wrappers for the standard algorithms that simplifies their use when applied to a whole container. The main idea is to get rid of .begin() and .end() and just specify the container on which the algorithm must be applied.

Then, I'd like to know if it's possible (and not stupid by the way) to infer the return type of my wrappers from the standard algorithm return type itself.

For the moment, I tried the following (for std::count):

template<class Cnt,
         class T>
inline 
auto count(Cnt _cnt, const T& _val) -> decltype(std::count){}

but it gave me an error at compile time:

Failed to specialize function template ''unknown-type' ragut::count(Cnt,const T &)'

I figured it might not be enough to just say decltype(std::count), and supposed it asked for a more specified argument like that:

decltype(std::count<std::iterator<std::input_iterator_tag,Cnt::value_type> >)

but this gave the same error.

I'd like to know then if it's actually not stupid and possible to do that.

Это было полезно?

Решение

decltype(x) denotes the type of the expression x. In other words, you're trying to create a function returning a function template (in the first case) or a function (in the second case). That won't work. You want the type of a call to std::count, like this:

template<class Cnt,
         class T>
inline 
auto count(Cnt _cnt, const T& _val) 
  -> decltype(std::count(std::begin(_cnt), std::end(_cnt), _val)))
{ }

Другие советы

It would work, if you specify the correct template arguments. In this case, those would be <typename Cnt::const_iterator, typename Cnt::value_type>

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top