Created
November 27, 2012 04:55
-
-
Save cbsmith/4152462 to your computer and use it in GitHub Desktop.
Demonstration of brace initialization as well as variadic templates.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// -*- compile-command: "clang++ -ggdb -o brace_initializer -std=c++0x -stdlib=libc++ brace_initializer.cpp" -*- | |
#include <string> | |
#include <ostream> | |
#include <memory> | |
#include <iostream> | |
#include <sstream> | |
#include <new> | |
class Foo { | |
public: | |
std::ostream& append(std::ostream& aStream) const { | |
return aStream << "Foo(x: " << x << " y: " << y << ")"; | |
} | |
long x; | |
std::string y; | |
}; | |
std::ostream& operator<<(std::ostream& aStream, const Foo& aFoo) { return aFoo.append(aStream); } | |
template <typename T, typename... Args> | |
std::unique_ptr<T> safeCreate(Args... args) { | |
try { | |
return std::unique_ptr<T>(new T{args...}); | |
} catch (...) { | |
return nullptr; | |
} | |
} | |
long long_from_string(const std::string aString) { | |
std::istringstream buffer; | |
long value; | |
buffer >> value; | |
return value; | |
} | |
int main(int argc, const char*const *const argv) { | |
if (argc < 3) { | |
return -1; | |
} | |
const long x_value = long_from_string(argv[1]); | |
const std::string y_value = argv[2]; | |
Foo stackFoo = { x_value, y_value }; | |
std::unique_ptr<Foo> heapFoo = safeCreate<Foo>(x_value, y_value); | |
std::unique_ptr<Foo> justAsGoodFoo(new (std::nothrow) Foo {x_value, y_value}); | |
std::cout << "stackFoo: " << stackFoo << std::endl; | |
std::cout << "heapFoo: " << *heapFoo << std::endl; | |
std::cout << "justAsGoodFoo: " << *justAsGoodFoo << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment