Comments (2)
  • Add a Comment
  • Edit
  • More Actions v
  • Quarantine this Entry

1 rollie42 commented Permalink

A simple applied example I wrote a couple months ago when learning this shows its usefulness:

 
template<typename T="T" typename="typename" T2="T2">
bool are_equal(const T & _v1, const T2 & _v2)
{
return _v1 == _v2;
}
 
template<typename T="T" typename="typename" T2="T2" typename...="typename..." Args="Args">
bool are_equal(const T & _v1, const T2 & _v2, Args... args)
{
return _v1 == _v2 && are_equal(_v1, args...);
}
 
struct foo
{
foo(int _bar){ m_bar = _bar; }
bool operator==(int _rhs){ return m_bar == _rhs; }
int m_bar;
};
 
bool operator==(int _lhs, const foo & _rhs){ return _rhs.m_bar == _lhs; }
 
int main()
{
foo myFoo(2);
cout << are_equal(1, 1, 1, myFoo, 2, 4, 1) << endl;
cout << are_equal(2, 2, 2, 2) << endl;
cout << are_equal(2.0f, 2, myFoo, 2.0) << endl;
return 0;
}</typename></typename>

2 Xavier.Nodet commented Permalink

Variadic templates have very interesting uses: in particular, they allow to write perfectly type-safe printf-like functions, or classes like std::tuple. <div>&nbsp;</div> You can find more information about their uses in the proposal that was brought forward the C++ standardization committee (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2080.pdf) or in Andrei Alexandrescu's talk at Going Native 2012 (http://youtu.be/_zgq6_zFNGY)