1

How do I import the type alias of a class for general use in my source file?

I.e., consider I have a file myClass.h with

template<typenmae T>
class myClass {
  using vec = std::vector<double>;
  
  vec some_vec_var;
public:
  // some constructor and other functions
  myClass(T var);
 
  vec some_function(vec some_var);
  void some_other_fcn(vec some_var);
};

I've always written my sourcefile (myclass.cpp) in the following manner

#include "myClass.h"

template<typename T> 
myClass<T>::myClass(T var){/* */} // fine 

template<typename T>
void myclass<T>::some_function(vec some_var){/* */} // fine

// Error: vec was not declared in this scope ... 
template<typename T> 
vec myClass<T>::some_function(vec some_var){/* */} // not fine

How do I overcome this? Type aliases tend to become tediously long, so simply replacing vec as return-type with its declared alias is not a feasable solution for me.

Do I need to wrap it around a namespace scope? something like

namespace MyNameSpace{
  class myClass { ... };
}

as described here: C++: Namespaces -- How to use in header and source files correctly? ?

Or can I just import the namespace of the class somehow?

ro_go
  • 90
  • 7
  • `typename myClass::vec myClass::some_function(typename myClass::vec some_var){/* */}`. Frankly, I'm more concerned with the whole `myClass` being (a) a template, and (b) implemented anywhere *other* than the header file. Barring explicit instantiation intentions, that's where it belongs. – WhozCraig Apr 19 '22 at 09:28
  • Could zou elaborate your concern a little more? I thought it is common practice to write two separate files `*.h` with class and function declarations and `*.cpp` with the actual code. – ro_go Apr 19 '22 at 09:35
  • @ro_go yes but not with templated classes - these need to be defined in the header file as well, since the compiler instantiates it for the specific types used inside the template; see [Why can templates only be implemented in header file](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – codeling Apr 19 '22 at 11:22

1 Answers1

2

Trailing return type (C++11) might help:

template<typename T> 
auto myClass<T>::some_function(vec some_var) -> vec
{/* */} 

Else you have to fully qualify:

template<typename T> 
typename myClass<T>::vec myClass<T>::some_function(vec some_var)
{/* */}
Jarod42
  • 203,559
  • 14
  • 181
  • 302