如何创建typedef结构的前向声明

问题描述 投票:10回答:1

我有一个包含类的1.h文件test.h。在这个类中有一个私有方法返回一个我不想做“公共”的类型的指针,但我希望能够将这个test.h文件包含在其他源文件中。

通常,在.h文件中使用前向声明很容易:

class Foo;

但问题是这种类型来自一个我无法改变的C文件(因为它是我不维护的其他代码)而且它是一个typedef

所以基本上我的test.cpp是:

// this type comes from a C file, cannot be changed to struct or class
typedef struct 
{
   int x;
} Foo;

#include "test.h"

static Foo foo;

Foo *Test::private_function()
{
  foo.x = 12;
  return &foo;
}

int Test::compute()
{
   auto *local_foo = private_function();
   return local_foo->x;
}

和我的test.h文件是:

#pragma once

struct Foo;

class Test
{
public:
  Test() {}
  int compute();
private:
  Foo *private_function();
};

尝试编译失败:

>g++ -std=c++11 -c test.cpp
In file included from test.cpp:10:0:
test.h:3:8: error: using typedef-name 'Foo' after 'struct'
test.cpp:7:3: note: 'Foo' has a previous declaration here

目前我的解决方法是返回void *并来回执行static_cast,但我没有找到最佳选择。有更好的解决方案吗?

(我检查了Forward declaration of a typedef in C++,但我测试了解决方案,它们似乎不适用于我的情况,也许我想做的更简单/不同 - 我只有.h和.cpp - 或者只是不可能)

c++ forward-declaration
1个回答
1
投票

归还这个:

//#include "SecretFoo.h"
struct SecretFoo {
  uintptr_t handle;
};

//#include "SecretFooImpl.h"
#include "SecretFoo.h"
#include "Foo.h" // definition of typedef struct {int x;} Foo;
Foo* Crack( SecretFoo foo ) {
  return reinterpret_cast<Foo*>(foo.handle);
}
SecretFoo Encase( Foo* foo ) {
  return {reinterpret_cast<uintptr_t>(foo)};
}

现在我们得到:

#include "SecretFooImpl.h"
static Foo foo;

SecretFoo Test::private_function()
{
  foo.x = 12;
  return Encase(&foo);
}

int Test::compute()
{
   auto *local_foo = Crack(private_function());
   return local_foo->x;
}

在你的标题中:

#pragma once
#include "SecretFoo.h"

class Test
{
public:
  Test() {}
  int compute();
private:
  SecretFoo private_function();
};

这归结为相同的二进制代码,但SecretFoo和配对的Crack / Encase函数提供了比void*更安全的类型。


这种技术有时用于C世界。 SecretFoo是一种处理;一个不透明的指针式结构。其中的数据(uintptr_t handle)在这种情况下只是一个演员指针;但它可能是一个指针指针或其他任何东西的指针。 CrackEncase方法是允许访问/创建SecretFoo的唯一方法。

© www.soinside.com 2019 - 2024. All rights reserved.