考虑以下分布在 3 个文件中的代码:
// secret.h
#pragma once
class Secret { /* ... */ };
// foo.h
#pragma once
#include "secret.h"
template <typename T>
class Foo {
public:
// Other members ...
void bar();
};
/* Definition is included inside 'foo.h' because Foo is a template class. */
template <typename T> void Foo<T>::bar() {
Secret s;
/* Perform stuff that depend on 'secret.h' ... */
}
// main.cpp
#include "foo.h"
int main() {
Foo<int> foo;
Secret secret; // <--- This shouldn't be allowed, but it is!
return 0;
}
所以我的问题是我想对Foo的用户隐藏Secret ,除非他们明确使用. 通常,这将通过包含in来完成。但是,这是不可能的,因为Foo是一个模板类,我不能将它的定义与它的声明分开。显式模板实例化不是一个选项。 #include "secret.h"
secret.h
foo.cpp
最终,我想知道这是否可以通过显式模板实例化以外的方式实现,如果可以,如何实现?谢谢!