Code duplication between typedefs and explicit instantiations

前端 未结 3 1149
独厮守ぢ
独厮守ぢ 2021-01-03 03:11

tree.h

template
class binary_operation : public node
{
// ... unimportant details ...

    unsigned evaluate() const;
         


        
相关标签:
3条回答
  • 2021-01-03 03:14

    Use a macro. You could write a header like

    I_HATE_MACROS(binary_operation<std::plus<unsigned>, '+'>, addition)
    I_HATE_MACROS(binary_operation<std::multiplies<unsigned>, '*'>, multiplication)
    

    Then you can do

    #define I_HATE_MACROS(a, b) typedef a b;
    

    Or

    #define I_HATE_MACROS(a, b) template class a;
    

    Then

    #include "DisgustingMacroHackery.h"
    
    0 讨论(0)
  • 2021-01-03 03:18

    This is invalid and rejected by implementations because a typedef name is used in the elaborated type specifier

    template class addition;
    

    The following is invalid too, because the Standard says that there must be a simple template id contained in the elaborated type specifier. Comeau online and GCC both accept it, though.

    template class addition::binary_operation;
    

    You could apply a pervert workaround though to be fully Standards compliant

    template<typename T> using alias = T;
    template class alias<multiplication>::binary_operation;
    

    At least I could not find it being invalid anymore on a quick glance over the spec.

    0 讨论(0)
  • 2021-01-03 03:23

    I ask my self, why do you actually write a .cpp file as you have templates and they should go either all in the header file or in a seprarate file e.g ".icc", which holds the stuff from the cpp file. I am not sure but tempalates definitions should always NOT be in a compilation unit.

    See -> Storing C++ template function definitions in a .CPP file

    0 讨论(0)
提交回复
热议问题