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

标签 c++ templates c++11 hash c++14

我正在尝试为我自己的类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> 的主模板(通过包含) (原始列出的代码中缺少)。

关于c++ - 部分专用模板的声明不完整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35646809/

相关文章:

c++ - 具有不同参数但相同代码的模板类方法

c++ - 在 C++ 中一次输出一个字母?

c++ - SSE 数据类型和原语

c++ - 在大小达到保留容量之前,是否可以对 vector 进行重新分配?

函数指针的 C++ 无效初始化错误

java - 如何在 spring webapp 中初始化 Velocity DateTool?

c++ - 将 vector 的 vector (二维数组)重置为零

c++ - 将 vector<reference_wrapper<int>> 传递给 vector<int>?

c++11 - ifstream 检查读取错误

c++ - 为什么即使流中有一些字符,in_avail() 也会输出零?