部分专用模板的声明不完整

Incomplete declaration of a partially specialized template

本文关键字:声明 专用      更新时间:2023-10-16

我正在尝试为我自己的类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;
};

测试手柄.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>;
}

英普尔.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>的主模板(通过包含)(原始列出的代码中缺少)。