1

I have the following code where I initialize a table of function pointers. The table is used when input file is parsed.

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 }
};

How can I update the code if the base class TorchModule is template class.

template<MODE mode>
class TorchModule { ... };
template<MODE mode>
class TorchLinear : public TorchModule<mode> { ... };
template<MODE mode>
class TorchView   : public TorchModule<mode> { ... };
Sergey Malashenko
  • 347
  • 1
  • 3
  • 8
  • 1
    not clear what you want to do; how will `TorchModule` being a template affect its subclasses? where will the template parameter `mode` be used? please provide a [mcve] – m.s. Jun 19 '16 at 07:25
  • this is still not a **complete** example; where is the `load_Object` being stored? is this a global variable? or a member of another type? where is it initialized? ... show how you use that map in you current implementation – m.s. Jun 19 '16 at 07:36

1 Answers1

2

You can define the table as a static variable in a template class.

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 }
};

Notes:

  • I used C++11 template aliases (using). For C++98, you can put a typedef into a template class instead.
  • There will be one instance of the table for every different mode it is used with.
  • With C++14, you can use a template variable instead of defining the table in a class.
  • Your code may become more readable if you put the whole thing into a class templated by mode, to avoid the template parameter propagating into all pieces of your solution.
Ambroz Bizjak
  • 7,809
  • 1
  • 38
  • 49
  • There may also be a need to use of the `template` and `typename` keywords inside templated `TorchModule` in some cases (related: http://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords) – W.F. Jun 19 '16 at 08:19