简体   繁体   English

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

[英]Incomplete declaration of a partially specialized template

I am trying to partially specialize the std::hash struct for my own class TestHandle , and this class has its implementation split up using the opaque pointer idiom. 我试图为我自己的类TestHandle专门化std::hash结构,并且使用不透明的指针习惯用法将该类的实现拆分开。 So I am trying to provide the impl class with its own std::hash specialization. 因此,我试图为impl类提供其自己的std::hash专用化。 But I am running into templating problems. 但是我遇到了一些问题。

Could someone help me understand why this is happening? 有人可以帮助我了解为什么会这样吗? I have attached all the necessary code below. 我已在下面附加了所有必需的代码。

TestHandle.h TestHandle.h

#pragma once
#include <memory>

class TestHandle {
public:
    TestHandle();

    void print();

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

TestHandle.cpp 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 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 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;
}

I am compiling with the following command 我正在使用以下命令进行编译

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

and am getting the following error 并收到以下错误

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

Just forward declares the specialisation. 正好宣告专业化。 It doesn't have to implement all the method (or any) of the original template. 它不必实现原始模板的所有方法(或任何方法)。 The compiler has no idea about the operator() . 编译器不了解operator()

You will need to define the struct (in place of just the declaration); 您将需要定义struct (代替声明);

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

Side note: you will also need to provide the primary template (via inclusion) of <functional> (missing in the original listed code). 旁注:您还将需要提供<functional>的主要模板(通过包含)(在原始列出的代码中缺失)。

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

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