Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
Mooophy committed Aug 20, 2015
1 parent 7ef6d2d commit 4eba146
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 34 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,6 @@

# ctags
*tags*

# vim
*.swp
46 changes: 12 additions & 34 deletions ch16/ex16.53.54.55/main.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
/***************************************************************************
* @file main.cpp
* @author Alan.W
* @author Yue Wang
* @date 16 Feb 2014
Aug, 2015
* @remark This code is for the exercises from C++ Primer 5th Edition
* @note
***************************************************************************/
Expand All @@ -12,7 +13,7 @@
//!
//! Exercise 16.54:
//! What happens if we call print on a type that doesn’t have an << operator?
// didn't compile.
// It didn't compile.
//!
//! Exercise 16.55:
//! Explain how the variadic version of print would execute if we declared
Expand All @@ -21,49 +22,26 @@
// error: no matching function for call to 'print(std::ostream&)'
//!


#include <iostream>

class Foo
{};

//! function to end the recursion and print the last element
//! this function must be declared before the variadic version of
//! print is defined
// trivial case
template<typename T>
std::ostream& print(std::ostream& os, const T& t)
std::ostream& print(std::ostream& os, T const& t)
{
return os << t;
//! ^
//! note: no seperator after the last element in the pack
}


//! this version of print will be called for all but the last element in the pack
// recursion
template<typename T, typename... Args>
std::ostream&
print(std::ostream &os, const T &t, const Args&... rest)
std::ostream& print(std::ostream& os, T const& t, Args const&... rest)
{
//! print the first argument
os << t << ",";

//! recursive call; print the other arguments
return print(os,rest...);
return print(os << t << ", ", rest...);
}


int main()
{
//! printing one argument
//print(std::cout, 1);

//! printing two arguments
print(std::cout, 1,2);

//! printing 5 arguments
//print(std::cout, 1,2,3,4,"sss");

//Foo foo,bar;
//print(std::cout,foo,bar);
print(std::cout, 1) << std::endl;
print(std::cout, 1, 2) << std::endl;
print(std::cout, 1, 2, 3, 4, "sss", 42.4242) << std::endl;

return 0;
}

0 comments on commit 4eba146

Please sign in to comment.