【问题标题】:Deriving a variable type based on another variable type in C++基于 C++ 中的另一个变量类型派生一个变量类型
【发布时间】:2015-08-16 02:59:36
【问题描述】:

我正在研究哈希函数的实现,主要基于 Carter 和 Wegman 技巧。根据输入空间的大小,所使用的素数需要足够长以形成稳健的散列,例如如果我想要一个 uint32_t 的哈希值,我将使用梅森素数 2^61-1,因此我需要一个 uint64_t;对于 uint16_t,我还需要 uint64_t 等。

到目前为止,我已经将它实现为具有两种类型的模板,但是由于我事先知道哪些类型与哪些类型相配,因此如果我可以将其实现为具有单一类型的模板会更方便。

到目前为止I have something like

    template<typename T1, typename T2>
    class Hash_CW2: public Hash<T1>{
        protected:
            T2 seeds[2];
            [...]
            void init(unsigned B, T2 seed0, T2 seed1);

        public:
            Hash_CW2(unsigned B, T2 seed0, T2 seed1);
            [...]
            virtual unsigned element(T1 j);
};

我想要类似的东西:

    template<typename T1, typename T2=GET_TYPE(T1)>
    class Hash_CW2: public Hash<T1>{
        [...]
};

知道怎么做吗?有可能吗?

非常感谢!

【问题讨论】:

标签: c++ templates hash


【解决方案1】:

使用模板专业化,您可以执行以下操作:

template <typename T>
struct hash_type_for;

template <>
struct hash_type_for<uint16_t>
{ using type = uint64_t; };

template <>
struct hash_type_for<uint32_t>
{ using type = uint64_t; };

template <typename T>
using hash_type_for_t = typename hash_type_for<T>::type;

然后像这样使用它:

template<typename T1, typename T2 = hash_type_for_t<T1>>
class Hash_CW2: public Hash<T1>{

或者,如果您希望 T2 仅根据 T1 计算,并且不希望用户能够更改它:

template<typename T1>
class Hash_CW2: public Hash<T1>{
    using hash_type = hash_type_for_t<T1>;

【讨论】:

  • 谢谢!这正是我想要的:)
猜你喜欢
  • 2018-05-22
  • 1970-01-01
  • 2019-08-05
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 2023-01-20
相关资源
最近更新 更多