簡體   English   中英

模板類中靜態方法的函數指針

[英]Function pointer on static method in template class

我有以下代碼在其中初始化函數指針表。 解析輸入文件時使用該表。

class TorchModule { ... };
class TorchLinear : public TorchModule { ... };
class TorchView   : public TorchModule { ... };
...
typedef std::shared_ptr<const TorchModule> ( *load_function )( File* file );

using table_type = std::map< std::string, load_function > table_type;

table_type load_Object = {
    {"nn.Linear", &TorchLinear::load },
    {"nn.View"  , &TorchView  ::load }
};

如果基類TorchModule是模板類,如何更新代碼。

template<MODE mode>
class TorchModule { ... };
template<MODE mode>
class TorchLinear : public TorchModule<mode> { ... };
template<MODE mode>
class TorchView   : public TorchModule<mode> { ... };

您可以在模板類中將表定義為靜態變量。

template<MODE mode>
using load_function = std::shared_ptr< const TorchModule<mode> > (*)( File* file );

template<MODE mode>
using table_type = std::map< std::string, load_function<mode> >;

template<MODE mode>
struct Table {
    static table_type<mode> table;
};

template<MODE mode>
table_type<mode> Table<mode>::table = {
    {"nn.Linear", &TorchLinear<mode>::load },
    {"nn.View"  , &TorchView<mode>  ::load }
};

筆記:

  • 我使用了C ++ 11模板別名(使用)。 對於C ++ 98,可以將typedef放到模板類中。
  • 表所使用的每種不同模式都有一個實例。
  • 使用C ++ 14,可以使用模板變量,而不是在類中定義表。
  • 如果將整個內容放入按模式進行模板化的類中,則代碼可能會變得更具可讀性,以避免模板參數傳播到解決方案的所有部分中。

暫無
暫無

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

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