繁体   English   中英

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

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

我有一堂课:

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>

在这种情况下,编译器不可能推断出AB ,因为不能保证所有MyClass<A, B>实例化都存在NestedClass 更多信息:

您可以通过假定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());
    }
};

暂无
暂无

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

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