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?

3
  • typename myClass<T>::vec myClass<T>::some_function(typename myClass<T>::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. Commented Apr 19, 2022 at 9: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. Commented Apr 19, 2022 at 9: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 Commented Apr 19, 2022 at 11:22

1 Answer 1

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)
{/* */}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.