// this could be some long running computation or I/O future<int> calculate_the_answer() { return async([] { this_thread::sleep_for(1s); return42; }); }
// Here is a resumable function future<void> coro(){ cout << this_thread::get_id() << " Started waiting... \n"; auto result = await calculate_the_answer(); cout << this_thread::get_id() << " : woke up, get " << result << endl; }
intmain(int argc, char* argv[]) { coro().get(); cout << this_thread::get_id() << ": back in main\n"; }
$ npm i babel-preset-es2015 babel-preset-stage-0 --save-dev
在目前目錄上新增.babelrc`
1 2 3
{ "presets": ["es2015", "stage-0"] }
這樣程式就能漲常執行。
Compile to ES5
當然,可能還有跑在Browser的需求,因此轉成ES5還是必須的。
1 2 3 4 5 6 7 8 9 10 11 12
$ babel test.js --out-file test.compiled.js $ node test.compiled.js /test/test.compiled.js:14 var ref = _asyncToGenerator(regeneratorRuntime.mark(function_callee() { ReferenceError: regeneratorRuntime is not defined at /test/test.compiled.js:14:31 `` 還是遇到問題。 #### Problem Solving ~~~bash $ npm i babel-polyfill --save-dev
printf(ANSI_COLOR_RED "This text is RED!" ANSI_COLOR_RESET "\n"); printf(ANSI_COLOR_GREEN "This text is GREEN!" ANSI_COLOR_RESET "\n"); printf(ANSI_COLOR_YELLOW "This text is YELLOW!" ANSI_COLOR_RESET "\n"); printf(ANSI_COLOR_BLUE "This text is BLUE!" ANSI_COLOR_RESET "\n"); printf(ANSI_COLOR_MAGENTA "This text is MAGENTA!" ANSI_COLOR_RESET "\n"); printf(ANSI_COLOR_CYAN "This text is CYAN!" ANSI_COLOR_RESET "\n"); return0; }
這方法簡單,不過麻煩的是要手動加上Color跟Reset標籤在文字前後。
C++11 Solution
突然想到可以用C++11的新特性User defined literal來簡化,可以減少不少手動置入的風險。也可以練習User defined literal的如何使用。
macro_rules! min { // base case ($x:expr) => ($x); // `$x` followed by at least one `$y,` ($x:expr, $($y:expr),+) => ( // call min! on the tail `$y` std::cmp::min($x, min!($($y),+)) ) }