部分专用模板的声明不完整
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;
};
测试手柄.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>
的主模板(通过包含)(原始列出的代码中缺少)。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 专用模板是否需要专用声明?
- 在实例化封闭类模板之后,我们可以声明模板类成员的部分专用化吗
- C++模板专用化中的声明范围
- 显式专用化 - 模板 ID 与任何模板声明都不匹配
- 静态声明专用类的接口指针数组
- 模板类专用化:模板 ID 与任何模板声明都不匹配
- enable_if在类声明之外实现的方法专用化
- 声明一个模板函数,将模板类友元的两个对象(仅)带到这两个专用化
- 为什么在标题上的结构中声明的模板不违反 ODR 并且专用化会违反 ODR
- 类模板专用化的前向声明
- 了解模板的声明、定义和专用化
- 如何为非类型模板类的专用化定义声明之外的方法
- 声明无法解决"实例化后的显式专用化"错误
- 如何声明模板的友元函数的专用化
- C++11:模板专用化的 constexpr 成员的标准参考需要额外声明
- 在友元模板专用化的声明中不允许使用Constexpr
- 在何处声明类成员模板的部分专用化
- 模板类中专用函数的声明
- 特定于 C++ 模板专用化的声明