C++ C++;模板:是否覆盖部分(但不是全部)默认参数?
当我遇到一个带有多个默认参数的模板时,例如C++ C++;模板:是否覆盖部分(但不是全部)默认参数?,c++,templates,default-arguments,C++,Templates,Default Arguments,当我遇到一个带有多个默认参数的模板时,例如 template<typename ID = int, typename PAYLOAD = std::string> class Foo{}; 我可以写一些类似于: typedef Foo<PAYLOAD=int> Bar; typedef Foo-Bar; 我正在处理另一个团队的预定义模板,其中包含许多默认参数,并且能够使用第二种方法似乎可以提高代码的清晰度 查看有关StackOverflow的文档和其他问题,这似乎是
template<typename ID = int, typename PAYLOAD = std::string>
class Foo{};
我可以写一些类似于:
typedef Foo<PAYLOAD=int> Bar;
typedef Foo-Bar;
我正在处理另一个团队的预定义模板,其中包含许多默认参数,并且能够使用第二种方法似乎可以提高代码的清晰度
查看有关StackOverflow的文档和其他问题,这似乎是不可能的,但我想知道是否有人可以解释为什么这不是一个功能 没有
不支持这样的模板类型。可以在左到右顺序指定类型,在Bjarne Stroustrup的设计和演化中, ,C++提到了对关键字参数的建议;但是,他们被拒绝了,因为
扩展组达成共识,即建议接近冗余,将导致与现有C++代码的兼容性问题,并会鼓励不应该鼓励的编程风格。
我想关键字模板参数也不包括在内,原因是相同的。如果你想简化你的生活,要么
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...>
{};
它使用
some_template
的默认参数,但将arg1替换为int
Afaik。这仅在Python中可能(可能也在其他脚本语言中)。在C++中,我没有办法知道。这是解决方法,例如,也可以使用一些构造器模式来实现一个接近于:bool f(double,double,double,double,double,double)
不会告诉您任何事情,bool f(Point&,Point&,double)
开始提示发生了什么:)对模板参数应用相同的推理。你很少需要超过3个——如果你需要,你的班级可能做得太多了。但是,如果你有一个简单的方法来模板化10个参数,这将鼓励人们这样做
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...>
{};
replacing_t<some_template<>,rep<1,int>>