簡體   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