前瞻性声明的缺点?

Luk*_*uke 10 c++ class objective-c forward-declaration incomplete-type

在C++和Objective-C中,我已经养成了向前声明任何不需要在头文件中定义的必要类的习惯,然后根据需要导入在源文件中定义这些类的头文件.

有没有这种情况不是一个好主意?

(我知道前向声明的一大缺点是不完整类型的有限可用性.出于这个问题的目的,假设在头文件中我只需要使用前向声明的类作为不完整的类型.)

par*_*mar 7

有时您可以巧妙地更改程序的语义而不会引发任何错误

class Foo;

template < typename T>
struct Trait
{
    static const int MY_TYPE = -1;
};

// Lets say this is Foo.h
//class Foo
//{
//};
//template<>
//struct  Trait<Foo>
//{
//  static const int MY_TYPE = 1;
//};

void TestFunction(Foo& f)
{
    std::cout << Trait<Foo>::MY_TYPE << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

考虑上面的代码,注释掉的代码存在于标题中.如果包含标题,TestFunction将打印1,否则为-1