简体   繁体   English

C ++模板函数默认值

[英]C++ template function default value

Is it possible to define the default value for variables of a template function in C++? 是否可以在C ++中为模板函数的变量定义默认值?

Something like below: 如下所示:

template<class T> T sum(T a, T b, T c=????)
{
     return a + b + c;
}

Try this: 尝试这个:

template<class T> T sum(T a, T b, T c=T())
{
     return a + b + c;
}

You can also put in T(5) if you are expecting an integral type and want the default value to be 5. 如果期望整数类型并且希望默认值为5,也可以输入T(5)。

It all depends on the assumptions that you can do about the type. 这完全取决于您可以对类型进行的假设。

template <typename T> T sum( T a, T b, T c = T() ) { return a+b+c; }
template <typename T> T sum2( T a, T b, T c = T(5) ) { return a+b+c; }

The first case, it only assumes that T is default constructible. 第一种情况,仅假定T是默认可构造的。 For POD types that is value inititalization (IIRC) and is basically 0 , so sum( 5, 7 ) will call sum( 5, 7, 0 ) . 对于值为值初始化(IIRC)且基本上为0 POD类型,因此sum( 5, 7 )将调用sum( 5, 7, 0 ) 5,7,0 sum( 5, 7, 0 )

In the second case you require that the type can be constructed from an integer. 在第二种情况下,您需要可以从整数构造类型。 For integral types, sum( 5, 7 ) will call sum( 5, 7, int(5) ) which is equivalent to sum( 5, 7, 5 ) . 对于整数类型, sum( 5, 7 )将调用sum( 5, 7, int(5) ) ,它等效于sum( 5, 7, 5 )

Yes you can define a default value. 是的,您可以定义一个默认值。

template <class T> 
T constructThird()
{
    return T(1);
}

template <class T> 
T test(T a, 
       T b, 
       T c = constructThird<T>())
{
    return a + b + c;
}

Unfortunately constructThird cannot take a and b as arguments. 不幸的是,constructThird不能将a和b作为参数。

Yes, there just needs to be a constructor for T from whatever value you put there. 是的,只需要从您输入的任何值开始为T构造一个即可。 Given the code you show, I assume you'd probably want that argument to be 0 . 给定您显示的代码,我假设您可能希望该参数为0 If you want more than one argument to the constructor, you could put T(arg1, arg2, arg3) as the default value. 如果要为构造函数提供多个参数,可以将T(arg1, arg2, arg3)为默认值。

Yes! 是!

However you should at least have an idea about what T could be or it's useless. 但是,您至少应该对T可能是或无用的有所了解。

You can't set the default value of template parameters for functions, ie this is forbidden: 您不能为函数设置模板参数的默认值,即禁止这样做:

template<typename T=int> void f(T a, T b);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM