Default template parameters with forward declaration

后端 未结 4 1530
太阳男子
太阳男子 2020-12-25 14:35

Is it possible to forward declare a class that uses default arguments without specifying or knowing those arguments?

For example, I would like to declare a boo

4条回答
  •  Happy的楠姐
    2020-12-25 15:03

    I don't think you can forward declare a template with default arguments unless the library in question provided its own forward declaration header. This is because you can't respecify the default arguments (even if they match... gcc will still report “error: redefinition of default argument”).

    So to the best of my knowledge the solution is for the library to supply a forward declaration header Foo_fwd.h:

    #ifndef INCLUDED_Foo_fwd_h_
    #define INCLUDED_Foo_fwd_h_
    template class Foo; // default U=char up here
    #endif
    

    and then the full implementation in Foo.h would be:

    #ifndef INCLUDED_Foo_h_
    #define INCLUDED_Foo_h_
    #include "Foo_fwd.h"
    template class Foo { /*...*/ }; // note no U=char here
    #endif
    

    So now your code could use Foo_fwd.h as well... but unfortunately, since this approach requires modifying the original Foo.h to remove the default arguments this doesn't scale to 3rd party libraries. Maybe we should lobby the C++0x crew to allow equivalent respecification of default template arguments, à la typedefs...?

提交回复
热议问题