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