'Using struct as a type in a C++ template?
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?
Solution 1:[1]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | balu |
