是否可以从模板生成函数作为 f() 和 f<T>()?

Is it possible to have functions generated from template as f() and f<T>()?

本文关键字:gt lt 函数 是否      更新时间:2023-10-16

是否可以将模板生成的函数为f()f<T>()

我想大部分时间都使用指定的类型来调用F,例如:

f<string>();
f<int>();

,但我还需要这样称呼:

f();

和未指定的类型应为字符串。这可能吗?

template <typename T>
void f() { ... }
void f() { f<string>(); }

您可以为模板参数提供默认类型:

template<class T=std::string>
foo()

注意:如果将默认参数转换为模板类,则必须用Foo<>声明默认版本。调用模板函数时,这不是必需的;您可以在没有角度括号的情况下调用默认版本:foo()

另一个注意事项:由于模板参数扣除而起作用。标准的报价(2012年1月草案§14.8.2.5)强调矿山:

由此产生的替换和调整后的功能类型用作 模板参数扣除的函数模板类型。如果 尚未推导模板参数,其默认模板参数, 如果有的话,可以使用。[示例:

template <class T, class U = double>
void f(T t = 0, U u = 0);
void g() {
    f(1, ’c’);     //f<int,char>(1,’c’)
    f(1);          //f<int,double>(1,0)
    f();           //error: T cannot be deduced
    f<int>();      //f<int,double>(0,0)
    f<int,char>(); //f<int,char>(0,0)
}
#include <string>
template <typename T=std::string>
void f() {}
int main()
{
  f();
}