1

I've looked through dozens of articles on this site and others and I can't find a single one which addresses this particular issue. Consider this SparseGraph class I'm working on:

Sparse_Graph.h

template <typename NodeType, typename EdgeType>
class SparseGraph
{
    //...
public:
    SparseGraph();
    //...
};

In order to shorten code in my .cpp file, I'm looking to do something similar to:

Sparse_Graph.cpp

#include "Sparse_Graph.h"

template<typename NodeType, typename EdgeType>
using SGraph = SparseGraph<NodeType, EdgeType>;

SGraph::SparseGraph() {}

This is particularly important to me since later on in this file I have a declaration for an iterator function written as:

template <typename NodeType, typename EdgeType>
typename SparseGraph<NodeType, EdgeType>::EdgeIterator& 
SparseGraph<NodeType, EdgeType>::EdgeIterator::operator++()

(yeah)

Particularly, the error I get when attempting this is:

invalid use of template-name 'SGraph' without an argument list

So my question is: how can I get this sort of thing to work so I don't have to write 3 line function headers all over my .cpp file?


enter image description here

AldenB
  • 133
  • 7
  • 2
    That's because `NodeType` and `EdgeType` are generic and not actual types. You'd need to say `using SGraph = SparseGraph`... (IIRC) – Charles May 07 '17 at 16:54
  • template using SGraph = SparseGraph::Node, SparseGraph::Edge>; Does not work. (I have a using declaration for Edge and Node in the class declaration). I assume that these don't qualify as actual types either. – AldenB May 07 '17 at 16:57
  • 1
    You can't put the implementation in .cpp file because the compiler must be able to see it at the places where the template gets instantiated for concrete types. [See this question](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file). – zett42 May 07 '17 at 17:17
  • 1
    A little correction. You can't put a *generic* implementation in .cpp file, but what you can do instead is use [explicit instantiation](http://stackoverflow.com/questions/115703/storing-c-template-function-definitions-in-a-cpp-file). – zett42 May 07 '17 at 17:23
  • So are you saying that without the explicit instantiation, what I'm looking for is impossible? – AldenB May 07 '17 at 17:24
  • 1
    Correct. That's why most template libraries are header-only. – zett42 May 07 '17 at 17:28

0 Answers0