我有一个类:
namespace App
{
template<typename A, typename B>
class MyClass
{
//...
class NestedClass
{
//...
}
}
} //namespace App
我想为 NestedClass 定义一个 std::hash
//Definition of hash functions
namespace std
{
//Definition of a hash to use generic pairs as key
template<typename A, typename B>
struct hash<App::MyClass<A,B>::NestedClass>
{
public:
size_t operator()(const App::MyClass<A,B>::NestedClass &it) const
{
return std::hash(it.toInt());
}
};
}
我收到错误:
source.h:1166: error: type/value mismatch at argument 1 in template parameter list for 'template<class _Tp> struct std::hash'
struct hash<App::MyClass<A,B>::const_NestedClass>
^
知道吗?谢谢!
您可以通过在
适当的位置添加typename
来修复错误,以通知编译器::
后面的符号确实是一种类型:
template<typename A, typename B>
struct hash<typename App::MyClass<A, B>::NestedClass>
{// ^^^^^^^^
public:
size_t operator()(const typename App::MyClass<A,B>::NestedClass &it) const
// ^^^^^^^^
{
return hash(it.toInt());
}
};
现在你得到一个新的错误:
prog.cc:22:12: error: class template partial specialization contains template parameters that cannot be deduced; this partial specialization will never be used [-Wunusable-partial-specialization]
struct hash<typename App::MyClass<A, B>::NestedClass>
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
prog.cc:21:23: note: non-deducible template parameter 'A'
template<typename A, typename B>
^
prog.cc:21:35: note: non-deducible template parameter 'B'
template<typename A, typename B>
编译器不可能推断出A
和B
在这种情况下,因为无法保证所有MyClass<A, B>
实例化都存在NestedClass
。更多信息:
SO:"模板部分专业化">
SO:"模板参数未用于部分专用化">
您可能可以通过假设NestedClass
存在并在MyClass<A, B>
上进行哈希处理来解决此问题。提供某种从MyClass
访问NestedClass
的方法,您将能够编写如下内容:
template<typename A, typename B>
struct hash<typename App::MyClass<A, B>>
{
public:
size_t operator()(const typename App::MyClass<A,B> &it) const
{
return hash(it.nested.toInt());
}
};