Search code examples
c++namespacestype-alias

Import type-alias from class in source


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?


Solution

  • 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)
    {/* */}