class MC_base { using O...">

Good practice of using "use" in C ++ templates

I have a small class that uses multiple STL lists inside

template<class T> class MC_base { using OBJ_LIST = std::list<T>; using OBJ_VAL = typename OBJ_LIST::value_type; using OBJ_ITR = typename OBJ_LIST::iterator; using OBJ_CITR = typename OBJ_LIST::const_iterator; OBJ_LIST A,B,C; ... }; 

Using using statements, if I write an iterator inside a class definition, it looks nice and clean:

 OBJ_ITR begin() { return A.begin(); }; OBJ_ITR end() { return A.end(); }; OBJ_CITR begin() const { return A.begin(); }; OBJ_CITR end() const { return A.end(); }; 

Writing new functions, again inside the class definition, is easy, as I can just use the names OBJ_XXXX if necessary. Also, if I decide to change the type of container (say, std::vector ) at some point later, I only need to change one line, and as long as my new container supports all the same actions, everything should be smooth.

This is problematic, however, when I want to define a new class function outside the class definition

 template<class T> OBJ_ITR MC_base<T>::foo(OBJ_ITR x) { ... } 

I am not sure how to "derive" the operators used so that they work correctly with templates, and not define them for every function that would be too verbose. In addition, I do not want to pollute the namespace with my operators.

Is there a way to use using with templates?

+4
source share
2 answers

You can use the return type. A type is scanned within the class, as is the case with parameter types, so nested types do not need to be qualified.

 template<class T> auto MC_base<T>::foo(OBJ_ITR x) -> OBJ_ITR { ... } 
+5
source

Outside the class, you need to define names. You also need to use the typename keyword to promise the compiler that these names are types in each specialization.

 template<class T> typename MC_base<T>::OBJ_ITR MC_base<T>::foo( typename MC_base<T>::OBJ_ITR x ) { ... } 

9.3p2 requires that

A member function is defined that appears outside the class definition. in the namespace area containing the class definition.

This prevents the use of a more nested scope to determine in which these names will be present. Not to mention that these names depend on the template parameter.


The best solution is probably to write these inline functions. These are members of the template class, so they should still be included in the header file.

+5
source

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


All Articles