简体   繁体   English

在 C++ 模板中使用 struct 作为类型?

[英]Using struct as a type in a C++ template?

I have a function like so我有一个 function 像这样

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其中 generatenums 是另一个模板化的 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?但这会产生很多错误,让我想知道为什么我不能将 struct 用作 C++ 模板的类型,是否有办法解决这个问题?

unordered_set on structs needs custom hash function.结构上的unordered_set需要自定义 hash function。

similarly uset on structs needs comparaor < operator to be defined.同样,结构上的uset需要定义 comparaor <运算符。

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM