在类模板实例化中为某些参数明确使用默认值

在类模板实例化中为某些参数明确使用默认值

本文介绍了在类模板实例化中为某些参数明确使用默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个类模板可以具有多个都具有默认值的参数.

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

template<typename UnderlyingT0 = int, typename UnderlyingtT1 = long, typename StringT = std::string>
struct options;

仅使用默认参数对模板进行设置很容易:

Instatiating the template with just default parameters is easy:

options<> my_default_options;

但是,如果我想更改参数的子集怎么办?

But what if I want to change a subset of parameters?

options<int, int, std::wstring> wstring_options;

int 不是第一个参数的默认值,而第二个参数不是默认值.是否有类似的东西

It is not obvious that int is a default for the first parameter while for the second it isn't. Is there something like

options<default, int, std::wstring> wstring_options;

在C ++中?

推荐答案

不,在标准C ++中没有可以启用此功能的东西.@FlorisVelleman在评论中指出的一种选择是引入别名模板:

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 <class UnderlyingT1, class StringT = std::string>
using options_defT0 = options<int, UnderlyingT1, StringT>;

这样做的缺点是必须在别名定义中显式复制 UnderlyingT0 的默认参数,但至少要在一个地方复制.

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.

许多Boost库使用一个替代选项.他们引入了一个特殊的标记 use_default 并将 that 设置为默认值.像这样:

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<typename UnderlyingT0 = use_default, typename UnderlyingtT1 = use_default, typename StringT = use_default>
struct options
{
  using RealUnderlyingT0 = typename std::conditional<
    std::is_same<UnderlyingT0, use_default>::value,
    int,
    UnderlyingT0
  >::type;

  using RealUnderlyingT1 = typename std::conditional<
    std::is_same<UnderlyingT1, use_default>::value,
    long,
    UnderlyingT1
  >::type;

  using RealStringT = typename std::conditional<
    std::is_same<StringT, use_default>::value,
    std::string,
    StringT
  >::type;
};

这里的缺点是1.您无法通过查看模板声明来告知默认参数,以及2. options<> options< int,long,std::string> 是不同的类型.

Here, the downsides are that 1. you cannot tell the default arguments by looking at the template declaration, and 2. options<> and options<int, long, std::string> 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.

这篇关于在类模板实例化中为某些参数明确使用默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 20:29