Created
August 31, 2019 07:11
-
-
Save munckymagik/d5da638bd044dcccf02645babe3c71b8 to your computer and use it in GitHub Desktop.
Trying out the features of C++11
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
// | |
// main.cpp | |
// Cpp11Tryout | |
// | |
// Created by Dan Munckton on 01/05/2014. | |
// Copyright (c) 2014 Dan Munckton. All rights reserved. | |
// | |
#include <iostream> | |
#include <functional> | |
// ----------------------------------------------------------------------------- | |
// Lambdas | |
// ----------------------------------------------------------------------------- | |
void callLambda() | |
{ | |
auto func = [] () { std::cout << "Hello World\n"; }; | |
func(); | |
} | |
//template<typename Func> | |
void callMyFunc(std::function<void (void)> func) | |
{ | |
func(); | |
} | |
void passALambda() | |
{ | |
callMyFunc([] () { | |
std::cout << "I was called\n"; | |
}); | |
} | |
void lambdaArguments() | |
{ | |
auto func = [] (std::string thingy) { | |
std::cout << "I was passed: " << thingy << "\n"; | |
}; | |
func("a char array that will be promoted to a std::string"); | |
} | |
void lambdaReturnValues() | |
{ | |
// Inferred return type first | |
auto func = [] () { return 1; }; | |
// Explicit return type | |
auto func2 = [] () -> int { return 2; }; | |
std::cout << "My first lambda returned: " << func() << "\n"; | |
std::cout << "My second lambda returned: " << func2() << "\n"; | |
} | |
void lambdaClosures() | |
{ | |
int a = 0; | |
int b = 0; | |
// Capture by reference | |
[&] { a = 1; b = 2; }(); | |
// Capture a by reference, b as a copy | |
[&a, b] { | |
a = b; | |
// b is effectively read only? Or at least Xcode says I can't assign to it | |
// b += 1; | |
}(); | |
// All captures are copies | |
[=] { | |
std::cout << "a=" << a << " b=" << b << "\n"; | |
}(); | |
} | |
void lambdaCalledInPlace() | |
{ | |
[] { std::cout << "I was called immediately\n"; }(); | |
} | |
int main(int argc, const char * argv[]) | |
{ | |
callLambda(); | |
passALambda(); | |
lambdaArguments(); | |
lambdaReturnValues(); | |
lambdaCalledInPlace(); | |
lambdaClosures(); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment