1

I'm relatively new to C++ and I feel like I'm in over my head. I'm trying to create a graph structure that can take any kind of data by using templates. Here is c_graph.h

#pragma once
#include <vector>
#include <unordered_map>
#include <unordered_set>

template <class T> class c_graph {
    private:
        std::unordered_map<T,std::unordered_set<T>> adj_matrix;

    public: 
        '' GRAPH OPERATIONS OMITTED ''
};

template <class M> struct node {
public:
    M val;

    node() {

    }

    node(M v) {
        val = v;
    }
};

I would like to support using data directly (hence the template T on the graph), or wrapping the data in a node struct, which is defined at the bottom. My reason for the node struct is sometimes you want different nodes in the graph to have the same data, which wouldn't work with the unordered_map on the outside of the adjacency matrix without a data wrapper.

However I've run into an issue with the unordered_set class. It doesn't have a hash function for node. I read about this problem online and the solution seems to be something like

namespace std {
    template <class M> class hash<node<M>> {
    public:
        size_t operator()(const node<M> &n) const
        {
            return reinterpret_cast<size_t>(&n);
        }
    };
};

I have another .cpp file that is trying to use c_graph<node<char>>

However for the life of me I can't get my code to compile. I've tried placing the hash snippet inside c_graph.h, where I get a bunch of linker errors

error LNK2019: unresolved external symbol "public: void __thiscall c_graph<struct node<char> >::add_node(struct node<char>)"... 

and I've tried placing it inside c_graph.cpp, where I get

error C2338: The C++ Standard doesn't provide a hash for this type.

1 Answers1

0

Turns out you can't really separate template function declarations from template function implementations. Linker error when using a template class?

Moving the contents of c_graph.cpp into c_graph.h got rid of the linker errors

Community
  • 1
  • 1