: 6. . .
3.01 21 2016.
() 2013-2016, , .., ,
-
. - 3 C:
● int abs (int)
● long labs (long)
● double fabs (double)
, , :
int abs (int _value)
{
return (_value < 0)? - value: value;
}
long labs (long _value)
{
return (_value < 0)? - value: value;
}
double fabs (double _value)
{
return (_value < 0)? - value: value;
}
- 3 , . ++ (.., ), , , , :
int abs (int _value)
{
return (_value < 0)? - value: value;
}
long abs (long _value)
{
return (_value < 0)? - value: value;
}
double abs (double _value)
{
return (_value < 0)? - value: value;
}
, . , , , Ctrl-C + Ctrl-V . , , , .
. , :
# define ABS_VALUE(_v) (((_v) < 0)? - (_v): (_v))
. , , :
● , :
○ , ;
○ ;
○ - , , ;
● , , ;
|
|
● , , , :
○ ( , 100% )
ABS_VALUE(a + b)
=>
(((a + b) < 0)? - (a + b): (a + b))
○ , :
ABS_VALUE(++a)
=>
(((++a) < 0)? - (++a): (++a))
(templates) - , . , . - , .
++, . , . ++ - STL (Standard Template Library - ), (), .
, , (generic programming). ++ - .
:
template < typename T >
Tabs (T _value)
{
return (_value < 0)? - value: value;
}
template , . - typename T , T. .
:
● (typename T);
● (T _value).
, - , .
typename class. . typename , T , , int. , class , .
T , . , T :
|
|
● ( T );
● 0 <;
● .
, , . , T :
struct Money
{
int m_dollars, m_cents;
Money (int _dollars, int _cents)
: m_dollars(_dollars), m_cents(_cents)
{
}
bool operator< (intvalue) const
{
return m_dollars < value;
}
Money operator - () const
{
return Money(- m_dollars, m_cents);
}
};
, , . - - , T. , . , !
. (instantiation) . T :
std::cout << abs< double >(-2.5);
std::cout << abs< int >(-2);
std::cout << abs< Money>(Money(-5, 20)).m_dollars;
(deduced) :
std::cout << abs(-2.5);
std::cout << abs(-2);
std::cout << abs(Money(-5, 20)).m_dollars;
T . , T.
- , .
, . , Microsoft , - , .. . 2 . :
template < typename T >
void f (T _val)
{
!
}
:
f(3);
error C2065: '': undeclared identifier
, GCC, , , .