[英]Can I forward-declare a typedef when its full type will have an as-yet-unknown form?
簡單版本的問題:
library.h
typedef library::whatever::something::complicated X;
我可以在不包含library.h的情況下轉發聲明X嗎?
基本上我想要做的是:
Foo.h:
// forward declare X
void foo (const X &);
Bar.h:
#include <library>
typedef library::type<blah>::whatever Bar;
typedef Bar X;
Foo.cpp:
#include <Foo.h>
#include <Bar.h>
foo (const X &) {...
main.cpp:
#include <Foo.h>
#include <Bar.h>
foo (X ());
前提是除非必須,否則我不想包含<library>
。 假設它與其他頭文件交互得很糟糕,但是這些其他頭文件需要聲明foo
。 如果沒有包含庫,就無法調用foo()
,但這會讓.cpps擔心。
如果我想讓X被類型化為普通的C類,那么向前聲明C就足夠了,但這在這里不起作用。
只有當我已經有了一個library::type<blah>
的定義(也許還有library::type<blah>
的定義)時,我可以將X轉發為typedef,但只能聲明為AFAIK。
前向聲明的重點是#include
這些類型的定義。
這是一個相關的問題:
namespace std
{
template <typename T>
class vector;
}
typedef std :: vector <int> Buffer;
void foo (const Buffer &);
#include <vector> // ok until here
int main ()
{
foo (Buffer ());
}
在這種情況下,std :: vector的前向聲明與定義不兼容。 讓我們假設我真的不想#include <vector>
(或者是任何外部類)。
有沒有解決的辦法?
我認為很難這樣做,因為typedef library::type<blah>::whatever Bar;
需要類庫:: type的完整定義,它不是可以解決的前向聲明。
你不能轉發聲明嵌套類,看到這個答案 。
但是,如果您的類沒有嵌套,您可以這樣做:
// inside library_fwd.hpp:
namespace library {
namespace whatever {
template <class T>
class Something;
typedef Something<int> IntSomething;
} // namespace whatever
} // namespace library
和:
// inside foo.cpp
#include "library_fwd.hpp"
void foo(const library::whatever::IntSomething&);
你的std :: vector示例的問題是關於沖突的聲明。 見std :: vector 。 固定:
namespace std {
template <class T>
class allocator;
template <typename T, class Allocator>
class vector;
}
typedef std::vector<int, std::allocator<int>> Buffer;
void foo(const Buffer &);
#include <vector> // now ok
int main () {
foo (Buffer ());
}
一些std lib前向聲明的PS示例: http : //en.cppreference.com/w/cpp/header/iosfwd
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.