c++ - 默认模板参数 - 不必来自对吗?为什么有效?

标签 c++ templates default-parameters

默认模板参数是否可以以不从右开始的方式使用“默认值”?

标准是什么?
编译器将如何解释?

例如,此代码有效 令我感到非常惊讶。

#include <iostream>
using namespace std;

template <bool T=true, class U>   //"default" from LEFT-most parameter
void f(U u){
    if(T){ cout<<true;}
    else cout<<false;
}
int main() {
    auto x = []( ){  };
    f(x);
    return 0;
}

在此处查看现场演示:https://ideone.com/l6d9du

最佳答案

模板参数推导在这里很有效,因为对于函数模板,后续的模板参数可能由函数参数推导。在这种情况下,模板参数 U可以从函数参数推导出 u .请注意,对于类模板,如您所料,默认模板参数之后的后续模板参数应具有默认模板参数或模板参数包。

§14.1/11 Template parameters [temp.param] :

If a template-parameter of a class template, variable template, or alias template has a default template-argument, each subsequent template-parameter shall either have a default template-argument supplied or be a template parameter pack. If a template-parameter of a primary class template, primary variable template, or alias template is a template parameter pack, it shall be the last template-parameter. A template parameter pack of a function template shall not be followed by another template parameter unless that template parameter can be deduced from the parameter-type-list ([dcl.fct]) of the function template or has a default argument ([temp.deduct]). A template parameter of a deduction guide template ([temp.deduct.guide]) that does not have a default argument shall be deducible from the parameter-type-list of the deduction guide template. [ Example:

template<class T1 = int, class T2> class B;   // error

// U can be neither deduced from the parameter-type-list nor specified
template<class... T, class... U> void f() { } // error
template<class... T, class U> void g() { }    // error

— end example ]

你可以尝试制作 U undeducible,看看会发生什么:

template <bool T=true, class U>   //"default" from LEFT-most parameter
void f(){
    if(T){ cout<<true;}
    else cout<<false;
}
int main() {
    f();            // Fail. Can't deduce U.
    f<true>();      // Fail. Can't deduce U.
    f<true, int>(); // Fine. T=true, U=int.
    return 0;
}

请注意,您必须明确指定所有模板参数才能使代码正常工作,这会使默认模板参数毫无意义。如果你想制作f()f<true>()工作,需要给U一个默认的模板参数(或使它成为模板参数包)。

template <bool T=true, class U=int>
void f(){
    if(T){ cout<<true;}
    else cout<<false;
}
int main() {
    f();              // Fine. T=true,  U=int
    f<false>();       // Fine. T=false, U=int
    f<false, char>(); // Fine. T=false, U=char
    return 0;
}

关于c++ - 默认模板参数 - 不必来自对吗?为什么有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39137281/

相关文章:

c++ - 什么时候应该使用模板而不是继承,反之亦然?

javascript - 在 JavaScript 中调用函数时正确指定参数值

Ruby 语法错误 : syntax error, 意外 '=',期望 ')'

C++ 错误 : Sleep was not declared in this scope

c++ - 如何在 Windows 上使用 Vim 中的开发者命令提示符命令行?

c++ - 从继承自模板的 dll 导出类

c++ - 模板参数依赖范围查找

c++ - 用 dft 粗略估计质心

c++ - 定义具有任意跨度的指针

C#,IntPtr 的默认参数值