Explicitly use defaults for some parameters in class template instantiation

后端 未结 4 1762
囚心锁ツ
囚心锁ツ 2021-02-18 14:42

A class template can have multiple parameters that all have defaults.

template

        
4条回答
  •  长发绾君心
    2021-02-18 14:58

    No, there is nothing in standard C++ which would enable this. One option, noted by @FlorisVelleman in the comments, is to introduce an alias template:

    template 
    using options_defT0 = options;
    

    This has the drawback of having to explicitly duplicate the default argument of UnderlyingT0 in the alias definition, but as least it' duplicated in one place only.

    An alternative option is used by many Boost libraries. They introduce a special tag use_default and make that the default value. Something like this:

    struct use_default {};
    
    template
    struct options
    {
      using RealUnderlyingT0 = typename std::conditional<
        std::is_same::value,
        int,
        UnderlyingT0
      >::type;
    
      using RealUnderlyingT1 = typename std::conditional<
        std::is_same::value,
        long,
        UnderlyingT1
      >::type;
    
      using RealStringT = typename std::conditional<
        std::is_same::value,
        std::string,
        StringT
      >::type;
    };
    

    Here, the downsides are that 1. you cannot tell the default arguments by looking at the template declaration, and 2. options<> and options are different types.

    The former can be fixed by good documentation, and the latter can probably be helped by judicious use of conversion functions and base classes.

提交回复
热议问题