How to make a template type work in this case?

Once again I want C ++ to have a stronger typedefs:

#include <vector>

template<typename T>
struct A {
    typedef std::vector<T> List;
};

template<typename T>
void processList(typename A<T>::List list) {
    // ...
}

int main() {
    A<int>::List list;
    processList<int>(list); // This works.
    processList(list);      // This doesn't.
}

Apparently, the compiler sees listhow std::vector<int>, and not A<int>::List, therefore, it cannot match it with the expected one A<T>::List.

In fact, this is a longer type name, often repeated, and this is a nuisance. Also, to processListaccept vectorinstead, is there a way to draw template type inference for me?

+3
source share
3 answers

Is there any way to draw template type inference for me?

No, this is what is called a non-deducible context.

? :

template<typename It>
void processList(It begin, It end) {
    typedef typename std::iterator_traits<It>::value_type T;
    // ....
}

int main() {
    A<int>::List list;
    processList(list.begin(), list.end()); // works now
    return 0;
}

( , vector , . .)

, , :

template<typename T, typename A, template<typename,typename> C>
void processList(C<T,A>& cont) {
    // ....
}

, . OTOH, std::map, .

+5

. , :

template<typename T>
class A : public std::vector<T> {
};

, .

0

:

template <class C>
void processList(C const& list)
{
  typedef typename C::value_type value_type;
  BOOST_STATIC_ASSERT_MSG((boost::same_type< C, typename A<value_type>::List >),
    NOT_A_A_LIST_TYPE,
    (C, A<value_type>)
  );
  // do your stuff
}

, ++ 0x !

template <typename second>
using TypedefName = SomeType<OtherType, second, 5>;

,

template <typename value>
using AList = typename A<value>::List;
0

Source: https://habr.com/ru/post/1753675/


All Articles