C++ 模板:覆盖一些但不是全部默认参数?

C++ Templates: override some, but not all, default arguments?

当我遇到带有多个默认参数的模板时,例如

template<typename ID = int, typename PAYLOAD = std::string>
class Foo{};

有没有办法让我只覆盖一些默认参数,而不是全部?

即而不是编写以下内容来创建 class,它使用整数而不是 std::string 作为 PAYLOAD 参数,

typedef Foo<int,int> Bar;

我可以写类似的东西吗:

typedef Foo<PAYLOAD=int> Bar;

我正在处理另一个团队的预定义模板,其中包含很多默认参数,能够使用第二种方法似乎可以提高我的代码的清晰度。

查看 Whosebug 上的文档和其他问题,似乎不可能,但我想知道是否有人可以解释为什么这不是一个功能?

没有

不支持这样的模板类型。可以按从左到右的顺序指定类型来代替默认值。

Bjarne Stroustrup 在《Design and Evolution of C++》中提到有关键字参数的提案;然而,他们被拒绝了,因为

the extensions group reached a consensus that the proposal was close to redundant, would cause compatibility problems with existing C++ code, and would encourage programming styles that ought not to be encouraged.

我想关键字模板参数未包含在内也是出于同样的原因。如果你想简化你的生活,要么 typedef 消除复杂性,要​​么编写适配器 类 重新排序模板参数。

如果模板只伪造类型,您可以用索引替换。

创建绑定前 n 个参数的模板。然后提取参数并替换您想要的参数。

这要求前 n 个参数在没有位置参数的情况下有效。

素描:

 template<class...>struct types{using type=types;};
 template<class types, class T, size_t index>
 struct replace{
   using type=/*types with index replaced with `T`*/;
 };
 template<template<class...>class Z,class types>
 struct apply;// applies content of types to Z
 template<size_t n, class T>struct rep{};
 template<class Z, class...reps>
 struct replacing;
 template<template<class...>class Z, class...Ts,class...reps>
 struct replacing<Z<Ts...>,reps...>:
   apply<Z,replacing_t<types<Ts...>,reps...>>
 {};
 template<class...Ts,class T0,class n,class...reps>
 struct replacing<types<Ts...>,rep<n,T0>,reps...>:
   replacing<replace_t<types<Ts...>,T0,n>,reps...>
 {};
 template<class...Ts>
 struct replacing<types<Ts...>>:
   types<Ts...>
 {};

_t 使用别名和一些操作留空。

那么您可以:

 replacing_t<some_template<>,rep<1,int>>

使用 some_template 的默认参数,但将 arg1 替换为 int