0

I have a function like so

template <typename T>
double vectortest(int n, bool prealloc) {
std::vector<T> tester;
    std::unordered_set<T> seq = generatenums<T>(n);
}

Where generatenums is another templatized function

template <typename T>
std::unordered_set<T> generatenums(int n) {
  std::unordered_set<T> ret;
}

Please note: I have truncated the entire contents of these functions, leaving only what I think is relevant to my question.

I also have a struct

typedef struct Filler
{
    int value;
    int padding[2500];
};

And I want to be able to invoke my functions like so

vectortest<Filler>(5, true);

But this generates a lot of errors, and leaves me wondering why I can't use struct as a type for C++ templates, and if there's a way around this?

Shisui
  • 1,051
  • 1
  • 8
  • 23
  • 3
    First, the `typedef` keyword does not belong there. Remove it. Then it already fails at `std::unordered_set`. `std::unordered_set` requires that you define `operator==` and a `std::hash` specialization. Then your `vectortest` and `generatenums` both are missing a return statement and no idea what `tester` is for. – user17732522 Mar 02 '22 at 06:53
  • 1
    Does this answer your question? [How can I use a C++ unordered\_set for a custom class?](https://stackoverflow.com/questions/38554083/how-can-i-use-a-c-unordered-set-for-a-custom-class) and [C++ unordered_map using a custom class type as the key](https://stackoverflow.com/questions/17016175/c-unordered-map-using-a-custom-class-type-as-the-key) (`unordered_set` and `unordered_map` have the same requirements) – user17732522 Mar 02 '22 at 06:54
  • You forgot to add the new alias for `typedef`. It is always worth reading what the error says. – Wais Kamal Mar 02 '22 at 07:44
  • C++'s error messages can be very scary, especially with templates. The way to read them is to scroll to the very top of the errors, and *only* read and handle the first error. Then try again. Most of the "lot of errors" are results of the first error, sort of "trickling down" if you will. – lionkor Mar 02 '22 at 09:19

1 Answers1

0

unordered_set on structs needs custom hash function.

similarlyuset on structs needs comparaor <operator to be defined.

#include <iostream>
#include <vector>
#include <unordered_set>


// class for hash function
template <typename T>
struct MyHashFunction {
    // id is returned as hash function
    size_t operator()(const T& f) const
    {
        return f.id;
    }
};

template <typename T>
double vectortest(int n, bool prealloc) {
std::vector<T> tester;
    std::unordered_set<T,MyHashFunction<T>> seq = generatenums<T>(n);
    return 73.0;
}

template <typename T>
std::unordered_set<T,MyHashFunction<T>> generatenums(int n) {
  std::unordered_set<T,MyHashFunction<T>> ret;

  return ret;
}

struct Filler
{
    int id;
    int value;
    int padding[2500];
};



int main(){
  
    
    vectortest<Filler>(5, true);
    return 0;
}
balu
  • 1,023
  • 12
  • 18