簡體   English   中英

部分專用模板的聲明不完整

[英]Incomplete declaration of a partially specialized template

我試圖為我自己的類TestHandle專門化std::hash結構,並且使用不透明的指針習慣用法將該類的實現拆分開。 因此,我試圖為impl類提供其自己的std::hash專用化。 但是我遇到了一些問題。

有人可以幫助我了解為什么會這樣嗎? 我已在下面附加了所有必需的代碼。

TestHandle.h

#pragma once
#include <memory>

class TestHandle {
public:
    TestHandle();

    void print();

    class Impl;
    std::unique_ptr<Impl> implementation;
};

TestHandle.cpp

#include "TestHandle.h"
#include "Impl.h"
#include <iostream>
using std::cout;
using std::endl;

TestHandle::TestHandle() : implementation{new TestHandle::Impl} { }

void TestHandle::print() {
    this->implementation->print();
    cout << "Hash of this->implementation is " 
        << std::hash<TestHandle::Impl>()(*this->implementation) << endl;
}

Impl.h

#pragma once
#include "TestHandle.h"
#include <functional>

class TestHandle::Impl {
public:

    void print();
    int inner_integer;
};

namespace std {
    template <> struct std::hash<TestHandle::Impl>;
}

Impl.cpp

#include "TestHandle.h"
#include "Impl.h"
#include <iostream>
using std::cout;
using std::endl;
#include <functional>

namespace std {
    template <> struct hash <TestHandle::Impl> {
        size_t operator() (const TestHandle::Impl& implementation) {
            return std::hash<int>()(implementation.inner_integer);
        }
    };
}

void TestHandle::Impl::print() {
    cout << "Printing from impl" << endl;
}

我正在使用以下命令進行編譯

g++ -std=c++14 -c Impl.cpp TestHandle.cpp

並收到以下錯誤

TestHandle.cpp:11:12: error: invalid use of incomplete type 'std::hash<TestHandle::Impl>'
<< std::hash<TestHandle::Impl>()(*this->implementation) << endl; 
template <> struct std::hash<TestHandle::Impl>;

正好宣告專業化。 它不必實現原始模板的所有方法(或任何方法)。 編譯器不了解operator()

您將需要定義struct (代替聲明);

template <> struct hash <TestHandle::Impl> {
        size_t operator() (const TestHandle::Impl& implementation) const noexcept;
    };

旁注:您還將需要提供<functional>的主要模板(通過包含)(在原始列出的代碼中缺失)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM