Created
July 3, 2014 11:24
-
-
Save inaz2/3ab3a05b9ee5c75d0107 to your computer and use it in GitHub Desktop.
C++11: auto and decltype
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
#include <iostream> | |
#include <string> | |
#include <vector> | |
#include <numeric> | |
#include <functional> | |
using namespace std; | |
template <typename T> | |
auto cube(T x) -> decltype(x) | |
{ | |
return x*x*x; | |
} | |
template <typename F, typename G, typename T> | |
auto compose(F f, G g) -> function<T(T)> | |
{ | |
return [=](T x){ return f(g(x)); }; | |
} | |
int main() | |
{ | |
cout << "[1] using string" << endl; | |
auto str = string("Hello, world!"); | |
cout << str << endl; | |
cout << "[2] using vector" << endl; | |
auto ary = vector<int>(4); | |
iota(ary.begin(), ary.end(), 0); | |
for (auto x : ary) { | |
cout << x << endl; | |
} | |
cout << "[3] using lambda function" << endl; | |
auto f = [](int x){ return x*x; }; | |
for (auto x : ary) { | |
cout << f(x) << endl; | |
} | |
cout << "[4] using template function" << endl; | |
auto g = cube<int>; | |
for (auto x : ary) { | |
cout << g(x) << endl; | |
} | |
auto G = cube<double>; | |
cout << G(1.1) << endl; | |
cout << "[5] using high-order function" << endl; | |
auto h = compose<decltype(f), decltype(g), int>(f, g); | |
for (auto x : ary) { | |
cout << h(x) << endl; | |
} | |
auto GG = compose<decltype(G), decltype(G), double>(G, G); | |
cout << GG(1.1) << endl; | |
return 0; | |
} |
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
$ g++ --version | |
g++ (GCC) 4.8.2 | |
Copyright (C) 2013 Free Software Foundation, Inc. | |
This is free software; see the source for copying conditions. There is NO | |
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | |
$ g++ --std=c++11 -o auto_and_decltype auto_and_decltype.cpp | |
$ ./auto_and_decltype | |
[1] using string | |
Hello, world! | |
[2] using vector | |
0 | |
1 | |
2 | |
3 | |
[3] using lambda function | |
0 | |
1 | |
4 | |
9 | |
[4] using template function | |
0 | |
1 | |
8 | |
27 | |
1.331 | |
[5] using high-order function | |
0 | |
1 | |
64 | |
729 | |
2.35795 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment