簡體   English   中英

如何包含同一標頭的兩個不同版本?

[英]How to include the two different versions of the same header?

我正在將文件轉換代碼從專有文件格式編寫為另一種通用格式。 我的目標是支持制造商文件格式的多個版本。

我有相同專有標頭的多個版本。 標頭定義了構成主文件標頭的各種結構(文件只是一個大標頭,后跟原始數據)。

我需要讀取源文件的前4個字節來確定文件版本。 反過來,文件版本會告訴我使用哪個版本的C結構來創建文件。

問題是:

  1. 我無法修改專有標題
  2. 標頭不使用名稱空間或類
  3. 標頭中定義了很多宏

可能的解決方案:

  • 為每種文件版本類型構建不同的轉換器二進制文件:-(
    • 用戶和開發人員都不方便
  • 動態加載每個版本的庫
    • 該轉換器是面向插件的,因此已經發生了很多此類情況

我曾嘗試使用名稱空間進行黑客入侵:

namespace version1 {
    #include "version1.h"
}

namespace version2 {
    #include "version2.h"
}

int main (void) {
    version1::header *hdr = new version1::header;
    return 0;
}

但是,由於包含保護,並且由於每個標頭中都重新定義了多個宏,因此無法使用。

有沒有一種優雅的方式來解決這個問題?

您可以使用兩個不同的源文件以及一個前向聲明:

// Forward declare in main.cpp:

namespace version1
{
   struct header;
}

namespace version2
{
   struct header;
}

// version1.cpp:

namespace version1
{
      #include <version1.h>
}

version1::header* new_v1_header()
{
   return new version1::header;
}

// other functions using `version1::header`

// version2.cpp:

namespace version2
{
      #include <version2.h>
}

version2::header* new_v2_header()
{
   return new version2::header;
}

// other functions using `version2::header`

另一種選擇是實現一個包裝器類,該包裝器的基類只是一個空殼:

class header_base
{
     virtual int func1(char *stuff) = 0; 
     ... many other virtual functions. 
};

// Create implementation of header_v1 or header_v2:
header_base* make_header(unsigned int magic);

header_base.cpp:

#include "header_v1.h"
#include "header_v2.h"

header_base* make_header(unsigned int magic)
{
    switch(magic)
    {
       case Magic_V1: 
          return new header_v1;
       case Magic_V2: 
          return new header_v2;
       default:
          assert(0);
          return 0;
    }
}

然后分別實施

在headerv1.h中:

class header_v1 : public header_base
{
    int func1(char *stuff);
    ... 
};

header_v1.cpp:

#include "header1.h"

int header_v1::func1(char *stuff)
{
   ... 
   return 17;
}

與header_v2.h和header_v2.cpp類似。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM