简体   繁体   English

定义模板类嵌套类的std :: hash的编译错误

[英]Compile error defining a std::hash for a template class nested class

I have a class: 我有一堂课:

namespace App
{

template<typename A, typename B>
class MyClass
{
    //...
    class NestedClass
    {
        //...
    }
}

} //namespace App  

I would like to define a std::hash for NestedClass 我想为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());
        }
    };
}

I get the error: 我得到错误:

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>
                                                  ^

Any idea? 任何想法? Thanks! 谢谢!

You can fix your error by adding typename where appropriate to inform the compiler that the symbol following :: is indeed a type: 您可以通过添加改正错误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());
    }
};

Now you get a new error: 现在,您会收到一个新错误:

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>

It is impossible for the compiler to deduce A and B in this context, as there's no guarantee that NestedClass exists for all MyClass<A, B> instantiations. 在这种情况下,编译器不可能推断出AB ,因为不能保证所有MyClass<A, B>实例化都存在NestedClass More information: 更多信息:

You'll probably be able to work around this by assuming that NestedClass exists and hashing on MyClass<A, B> instead. 您可以通过假定NestedClass存在,并在MyClass<A, B>上进行哈希处理来解决此问题。 Provide some way of accessing NestedClass from MyClass and you'll be able to write something like this: 提供某种从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());
    }
};

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

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