【发布时间】:2017-12-24 22:41:47
【问题描述】:
我正在尝试专门化哈希以包含所有算术类型的 std::vector,但它会引发一些错误
./includes/helpers.hpp:14:22: error: default template argument in a class template partial specialization
typename = std::enable_if_t<std::is_arithmetic<dtype>::value> >
^
./includes/helpers.hpp:16:8: error: class template partial specialization contains a template parameter that cannot be deduced; this partial specialization will never be used [-Wunusable-partial-specialization]
struct hash<std::vector<dtype> >
^~~~~~~~~~~~~~~~~~~~~~~~~
我尝试使用不同的 enable_if_t 指南尽可能接近。但它似乎不起作用,我做错了什么?
它似乎在不使用 enable_if_t 的情况下工作。但是可能会与不应该使用此哈希的向量发生冲突
这是我目前的代码(编辑得更“完整”)
#include <iostream>
#include <type_traits>
#include <vector>
namespace std {
template <typename dtype,
typename = std::enable_if_t< std::is_arithmetic<dtype>::value> >
struct hash<std::vector<dtype> > {
size_t operator()(const std::vector<dtype> &input)
{
//perform hash
}
};
}
using namespace std;
int main()
{
const vector<int> i{1,2,3,4};
cout << hash<vector<int>>()(i) << endl;
return 0;
}
【问题讨论】:
-
我从来没有遇到过这样的
enable_if_t应用程序作为未命名模板参数的默认值。您能否提供您提到的指南的链接? -
@Omni 这不是一个真正的指南,但我只是使用了两个不同的来源,希望它能正常工作。对于“未命名模板的默认值”en.cppreference.com/w/cpp/types/enable_if 说它应该可以工作(向下滚动到数字 5)。
-
为什么不把
static_assert(std::is_arithmetic<dtype>::value, "!");放在结构体中? -
@RSahu 希望这更完整
标签: c++ templates vector template-specialization