cheby_coeff::cheby_coeff(const mxArray *c_in){ if (!is_valid_input(c_in)){ throw std::runtime_error("cheby_coeff constructor called with invalid input"); } s=mxGetNumberOfElements(c_in); m=mxGetNumberOfElements(mxGetCell(c_in,0)); c.resize(s); double *pr_tmp; for (int ks=0;ks<s;ks++){ c[ks].resize(m); pr_tmp=mxGetPr(mxGetCell(c_in,ks)); copy(pr_tmp,pr_tmp+m,c[ks].begin()); } }
int main() { vector<string> p; p.push_back("this is an"); p.push_back("example"); p.push_back("to"); p.push_back("illustrate"); p.push_back("framing"); ostream_iterator<string> ofile(cout, "\n"); copy(p.begin(), p.end(), ofile); cout << endl; vector<string> f = frame(p); copy(f.begin(), f.end(), ofile); cout << endl; vector<string> h = hcat(frame(p), p); copy(h.begin(), h.end(), ofile); cout << endl; return 0; }
void AnalyzerManager::processNode(GNode* node, const vector<int>& context) { string tag = "AnalyzerManager"; Logger::d(tag) << "analysis node " << node->getIndex() << endl; copy(context.begin(), context.end(), ostream_iterator<int>(Logger::d(tag), "->\n")); if (mAnalyzersMap.find(node->getTreeCode()) != mAnalyzersMap.end()) { //cout<<node->getTreeCode()<<endl; vector<BaseAnalyzer*> &analyzerVector = mAnalyzersMap[node->getTreeCode()]; for (vector<BaseAnalyzer*>::iterator itor = analyzerVector.begin(); itor != analyzerVector.end(); ++itor) { (*itor)->analyzeNode(node, context); } } }
int main() { vector<int> vec{1, 2, 3, 4, 5, 6, 7, 8, 9}; vector<int> vec1, vec2; list<int> lst; auto it1 = back_inserter(vec1); auto it2 = front_inserter(lst); auto it3 = inserter(vec2, vec2.begin()); copy(vec.begin(), vec.end(), it1); for (auto& x : vec1) { cout << x << ' '; } cout << endl; copy(vec.begin(), vec.end(), it2); for (auto& x : lst) { cout << x << ' '; } cout << endl; copy(vec.begin(), vec.end(), it3); for (auto& x : vec2) { cout << x << ' '; } cout << endl; return 0; }
// The output buffer should be at least 256 bytes long. This used to use // a std::string but it worked about 50% slower, so this is somehow // unsafe but a lot faster. uint32_t DNS::compose_name(const uint8_t* ptr, char* out_ptr) const { const uint8_t* start_ptr = ptr; const uint8_t* end = &records_data_[0] + records_data_.size(); const uint8_t* end_ptr = 0; char* current_out_ptr = out_ptr; while (*ptr) { // It's an offset if ((*ptr & 0xc0)) { if (ptr + sizeof(uint16_t) > end) { throw malformed_packet(); } uint16_t index; memcpy(&index, ptr, sizeof(uint16_t)); index = Endian::be_to_host(index) & 0x3fff; // Check that the offset is neither too low or too high if (index < 0x0c || (&records_data_[0] + (index - 0x0c)) >= end) { throw malformed_packet(); } // We've probably found the end of the original domain name. Save it. if (end_ptr == 0) { end_ptr = ptr + sizeof(uint16_t); } // Now this is our pointer ptr = &records_data_[index - 0x0c]; } else { // It's a label, grab its size. uint8_t size = *ptr; ptr++; if (ptr + size > end || current_out_ptr - out_ptr + size + 1 > 255) { throw malformed_packet(); } // Append a dot if it's not the first one. if (current_out_ptr != out_ptr) { *current_out_ptr++ = '.'; } copy(ptr, ptr + size, current_out_ptr); current_out_ptr += size; ptr += size; } } // Add the null terminator. *current_out_ptr = 0; if (!end_ptr) { end_ptr = ptr + 1; } return end_ptr - start_ptr; }
int main() { // demonstrate match_results::format string result("The URL '"); string tail("' was found."); regex rgx("http://([^/: ]+)"); string text("The site http://www.petebecker.com has" " useful information."); smatch match; if (regex_search(text, match, rgx)) { // show result of successful match copy(tail.begin(), tail.end(), match.format(back_inserter(result), "$&")); cout << result << '\n'; } return 0; }
int main() { istream_iterator<int>int_it(cin); //reads ints from cin istream_iterator<int>int_eof; //end iterator value vector<int>v(int_it, int_eof); //initialize v by reading cin sort(v.begin(), v.end()); ostream_iterator<int>out(cout, " "); //writes ints to cout unique_copy(v.begin(), v.end(), out); //write unique elements to cout cout << endl; //write a newline after the output ofstream out_file("data"); //writes int to named file ostream_iterator<int>out_iter(out_file, " "); copy(v.begin(), v.end(), out_iter); out_file << endl; //write a newline at end of the file getchar(); }
T* newCopy(const T *src, size_t src_size, size_t dest_size) { assert(dest_size >= src_size); T *dest = new T[dest_size]; try { copy(src, src + src_size, dest); } catch (...) { delete[] dest; throw; } return dest; }
DocumentInfo& DocumentInfo::operator=(const DocumentInfo& other) { if (this != &other) { m_title = other.m_title; m_location = other.m_location; m_type = other.m_type; m_language = other.m_language; m_timestamp = other.m_timestamp; m_labels.clear(); copy(other.m_labels.begin(), other.m_labels.end(), inserter(m_labels, m_labels.begin())); } return *this; }
void first_permutation(int idx){ char p[16]={}; char pp[16]={}; for ( int i=0; i<len; ++i ) p[i] = i; for ( int i=len-1; i>0; --i ) { int d = idx / fact[i]; count[i] = d; idx = idx % fact[i]; copy( &p[0], &p[i+1], &pp[0] ); for ( int j=0; j<=i; ++j ){ p[j] = j+d <= i ? pp[j+d] : pp[j+d-i-1]; } } this->p.assign(p, 16); }
/** * @brief Converts a url into a local filename. * * @retval fn a character buffer to hold the local filename. * @param nfn the number of elements in the buffer @p fn points to. */ bool doc2::filename(char * fn, const size_t nfn) { using std::copy; using std::string; fn[0] = '\0'; const char * s = 0; const std::string protocol = this->url_protocol(); if (protocol == "file") { # ifdef _WIN32 string name = URI(this->url_).getPath().substr(1); # else string name = URI(this->url_).getPath(); # endif size_t len = (name.length() < (nfn - 1)) ? name.length() : nfn - 1; copy(name.begin(), name.begin() + len, fn); fn[len] = '\0'; return true; } else if (protocol == "http") { // // Get a local copy of http files. // if (this->tmpfile_) { // Already fetched it s = this->tmpfile_; } else if ((s = the_system->http_fetch(this->url_.c_str()))) { tmpfile_ = new char[strlen(s)+1]; strcpy(tmpfile_, s); free(const_cast<char *>(s)); // assumes tempnam or equiv... s = tmpfile_; } } // Unrecognized protocol (need ftp here...) else { s = 0; } if (s) { strncpy( fn, s, nfn-1 ); fn[nfn-1] = '\0'; } return s && *s; }
void explode_by_first_of(const std::string& text, const std::string& separator, std::vector<std::string>& results) { std::string::size_type found; std::string copy(text); do { found = copy.find_first_of(separator); if(found > 0){ results.push_back(copy.substr(0, found)); } copy = text.substr(found + 1); } while(found != std::string::npos); if(results.empty()) { results.push_back(text); } return; }
int main(int argc, const char * argv[]) { ifstream in(argv[1]); vector<string> lines; copy(istream_iterator<string>(in), istream_iterator<string>(), back_inserter(lines)); in.close(); for(int i = 0; i < lines.size(); ++i){ cout << sumOfDigits(strToInt(lines[i])) << "\n"; } return 0; }
void explode(const string& text, const string& separator, vector<string>& results) { string::size_type found; string copy(text); const string::size_type separator_size = separator.length(); do { found = copy.find(separator); if(found > 0){ results.push_back(copy.substr(0, found)); } copy = copy.substr(found + separator_size); } while(found != string::npos); if(results.empty()) { results.push_back(text); } return; }
/** // Constructor. // // @param grammar // The ParserGrammar to generate this ParserStateMachine from. // // @param error_policy // The error policy to report errors during generation to or null to // silently swallow errors. */ ParserStateMachine::ParserStateMachine( ParserGrammar& grammar, ParserErrorPolicy* error_policy ) { ParserGenerator parser_generator( grammar, error_policy ); if ( parser_generator.errors() == 0 ) { identifier_ = parser_generator.identifier(); actions_.swap( parser_generator.actions() ); productions_.swap( parser_generator.productions() ); symbols_.swap( parser_generator.symbols() ); states_.reserve( parser_generator.states().size() ); copy( parser_generator.states().begin(), parser_generator.states().end(), back_inserter(states_) ); start_symbol_ = parser_generator.start_symbol(); end_symbol_ = parser_generator.end_symbol(); error_symbol_ = parser_generator.error_symbol(); start_state_ = parser_generator.start_state(); lexer_state_machine_.reset(); } }
void Server::handleRequest(shared_ptr<tcp::socket> socket, Logger log) { // ProfilerStart("/home/sowa/local_workspace/pje/log/server.perf"); Server* server = this; vector<char> buffer(1024*1024); error_code error; socket->read_some(boost::asio::buffer(buffer), error); string request(buffer.size(), 0); copy(buffer.begin(), buffer.end(), request.begin()); string remoteIp = socket->remote_endpoint().address().to_string(); log.info("received request from " + remoteIp); string query = server->retrieveQuery(request); log.debug("query: \"" + query + "\""); string command = server->retrieveCommand(query); StrStrMap args = server->retrieveArgs(query, server->workDir()); string argsString = "{"; for (StrStrMap::const_iterator i = args.begin(); i != args.end(); ++i) { argsString += i->first + ": " + i->second + ", "; } argsString = argsString.substr(0, argsString.size() - 2); argsString += "}"; log.info("executing command <" + command + "> with args " + argsString); int tries = 10; while (tries) { try { Command::execute(*server, socket, command, args, log); tries = 0; } catch(const std::bad_alloc&) { --tries; if (tries) { _log.error("not enough memory to complete task: retrying"); boost::this_thread::sleep(boost::posix_time::seconds(3)); } else { _log.error("not enough memory to complete task: giving up"); } } } socket->close(); // ProfilerStop(); }
Packet2Blob::Packet2Blob(char const* blob, uint16_t length) : Packet(mId), blob(NULL), blobLength(length) { if (length > Packet::MAX_LOAD_SIZE) { throw InvalidSizeException("Blob to big", shared_from_this()); } uint16_t totalLength = blobLength + Packet::MIN_SIZE; packedData = new char[totalLength]; dataLength = totalLength; this->blob = packedData + OFFSET_DATA; packHeader(); copy(blob, blob + blobLength, stdext::make_checked_array_iterator<char*>(this->blob, blobLength)); packed = true; unpacked = true; }
int main(int argc, const char * argv[]) { // Open in the file argument ifstream in(argv[1]); // Create vector to hold lines from arg vector<string> lines; // Copy file to lines copy(istream_iterator<string>(in), istream_iterator<string>(), back_inserter(lines)); // Close file in.close(); // Convert read in strings to ints and store in vector<int> vector<int> nums(lines.size()); for(int i = 0; i < lines.size(); ++i){ nums[i] = strToInt(lines[i]); } vector<int> printPrimes; // Find and print all primes from ints using Sieve of Eratosthenes for(int i = 0; i < nums.size(); ++i){ int n = nums[i]; cout << "\n"; printPrimes = sieve(n); for(int i = 0; i < printPrimes.size(); ++i){ if(i != printPrimes.size() - 1){ cout << printPrimes[i] << ","; } else{ cout << printPrimes[i]; } } } return 0; }
CalcNode& CalcNode::operator=(const CalcNode &src) { number = src.number; coords = src.coords; copy(src.values, src.values + VALUES_NUMBER, values); crackDirection = src.crackDirection; damageMeasure = src.damageMeasure; bodyId = src.bodyId; rho = src.rho; materialId = src.materialId; contactNodeNum = src.contactNodeNum; contactDirection = src.contactDirection; publicFlags = src.publicFlags; privateFlags = src.privateFlags; errorFlags = src.errorFlags; borderConditionId = src.borderConditionId; contactConditionId = src.contactConditionId; rheologyMatrix = src.rheologyMatrix; return *this; }
template <typename T, typename MemoryBlock> void load( archive & ar , std::string const & path , alps::numeric::matrix<T,MemoryBlock> & m , std::vector<std::size_t> chunk = std::vector<std::size_t>() , std::vector<std::size_t> offset = std::vector<std::size_t>() ) { using std::copy; if(ar.is_data(path + "/size1") && ar.is_scalar(path + "/size1")) { // Old matrix hdf5 format std::size_t size1(0), size2(0), reserved_size1(0); ar[path + "/size1"] >> size1; ar[path + "/size2"] >> size2; ar[path + "/reserved_size1"] >> reserved_size1; std::vector<T> data; ar[path + "/values"] >> data; alps::numeric::matrix<T,MemoryBlock> m2(reserved_size1,size2); assert(m2.capacity().first == reserved_size1); copy(data.begin(), data.end(), col(m2,0).first); m2.resize(size1,size2); swap(m, m2); return; }
double* BackpropagationPerceptron::evaluate(double* input_row) { copy(input_row, input_row + layer_neuron_count_[0], answers_[0]); for (size_t i = 0; i < layers_count_ - 1; i++) { if (add_const_x_) { answers_[i][layer_neuron_count_[i]] = 1.0; } //answers[i + 1] = (answers[i] * W) Matrix::multiply_row_with_rows_to_row(answers_[i], *W_[i], answers_[i + 1]); //1 / (1 + e^( -answers * W)) for (size_t j = 0; j != layer_neuron_count_[i + 1]; j++) { answers_[i + 1][j] = 1.0 / (1 + pow(M_E, -answers_[i + 1][j])); } } double *result = new double[layer_neuron_count_[layers_count_ - 1]]; for (size_t i = 0; i != layer_neuron_count_[layers_count_ - 1]; i++) { result[i] = answers_[layers_count_ - 1][i]; } return result; }
int main(int argc, const char * argv[]) { int array[11]; auto restore = [&](int * x){ x[0] = 12; x[1] = 2; x[2] = 16; x[3] = 30; x[4] = 8; x[5] = 28; x[6] = 4; x[7] = 10; x[8] = 20; x[9] = 6; x[10] = 18; }; restore(array); alpaca::sort<int>(alpaca::BUBBLE_SORT, array, 11); copy(array, array + 11, ostream_iterator<int>(cout, " ")); cout << '\n'; restore(array); alpaca::sort<int>(alpaca::COCKTAIL_SORT, array, 11); copy(array, array + 11, ostream_iterator<int>(cout, " ")); cout << '\n'; restore(array); alpaca::sort<int>(alpaca::INSERTION_SORT, array, 11); copy(array, array + 11, ostream_iterator<int>(cout, " ")); cout << '\n'; restore(array); alpaca::sort<int>(alpaca::SELECTION_SORT, array, 11); copy(array, array + 11, ostream_iterator<int>(cout, " ")); cout << '\n'; restore(array); alpaca::sort<int>(alpaca::SHELL_SORT, array, 11); copy(array, array + 11, ostream_iterator<int>(cout, " ")); cout << '\n'; restore(array); alpaca::sort<int>(alpaca::QUICK_SORT, array, 11); copy(array, array + 11, ostream_iterator<int>(cout, " ")); cout << '\n'; return 0; }
/// Sets the document's labels. void DocumentInfo::setLabels(const set<string> &labels) { copy(labels.begin(), labels.end(), inserter(m_labels, m_labels.begin())); }
//execute all the plans in the usual manner without robustness checking void executePlans(int & argc,char * argv[],int & argcount,TypeChecker & tc,const DerivationRules * derivRules,double tolerance,bool lengthDefault,bool giveAdvice) { Ranking rnk; Ranking rnkInv; vector<string> failed; vector<string> queries; while(argcount < argc) { string name(argv[argcount]); plan * the_plan = getPlan(argc,argv,argcount,tc,failed,name); if(the_plan == 0) continue; plan * copythe_plan = new plan(*the_plan); plan * planNoTimedLits = new plan(); vector<plan_step *> timedInitialLiteralActions = getTimedInitialLiteralActions(); double deadLine = 101; //add timed initial literals to the plan from the problem spec for(vector<plan_step *>::iterator ps = timedInitialLiteralActions.begin(); ps != timedInitialLiteralActions.end(); ++ps) { the_plan->push_back(*ps); }; //add actions that are not to be moved to the timed intitial literals otherwise to the plan to be repaired //i.e. pretend these actions are timed initial literals for(pc_list<plan_step*>::const_iterator i = copythe_plan->begin(); i != copythe_plan->end(); ++i) { planNoTimedLits->push_back(*i); }; copythe_plan->clear(); delete copythe_plan; PlanRepair pr(timedInitialLiteralActions,deadLine,derivRules,tolerance,tc,current_analysis->the_domain->ops, current_analysis->the_problem->initial_state, the_plan,planNoTimedLits,current_analysis->the_problem->metric,lengthDefault, current_analysis->the_domain->isDurative(),current_analysis->the_problem->the_goal,current_analysis); PlanExecutionTracker pet(State(&(pr.getValidator()),current_analysis->the_problem->initial_state),&(pr.getValidator())); State::addObserver(&pet); if(LaTeX) { latex.LaTeXPlanReport(&(pr.getValidator()),the_plan); } else if(Verbose) pr.getValidator().displayPlan(); bool showGraphs = false; try { if(pr.getValidator().execute()) { if(LaTeX) *report << "Plan executed successfully - checking goal\\\\\n"; else if(!Silent) cout << "Plan executed successfully - checking goal\n"; if(pr.getValidator().checkGoal(current_analysis->the_problem->the_goal)) { if(!(pr.getValidator().hasInvariantWarnings())) { rnk[pr.getValidator().finalValue()].push_back(name); if(!Silent && !LaTeX) *report << "Plan valid\n"; if(LaTeX) *report << "\\\\\n"; if(!Silent && !LaTeX) *report << "Final value: " << pr.getValidator().finalValue() << "\n"; } else { rnkInv[pr.getValidator().finalValue()].push_back(name); if(!Silent && !LaTeX) *report << "Plan valid (subject to further invariant checks)\n"; if(LaTeX) *report << "\\\\\n"; if(!Silent && !LaTeX) *report << "Final value: " << pr.getValidator().finalValue(); }; if(Verbose) { pr.getValidator().reportViolations(); }; } else { failed.push_back(name); *report << "Goal not satisfied\n"; if(LaTeX) *report << "\\\\\n"; *report << "Plan invalid\n"; ++errorCount; }; } else { failed.push_back(name); ++errorCount; if(ContinueAnyway) { if(LaTeX) *report << "\nPlan failed to execute - checking goal\\\\\n"; else cout << "\nPlan failed to execute - checking goal\n"; if(!pr.getValidator().checkGoal(current_analysis->the_problem->the_goal)) *report << "\nGoal not satisfied\n"; } else *report << "\nPlan failed to execute\n"; }; if(pr.getValidator().hasInvariantWarnings()) { if(LaTeX) *report << "\\\\\n\\\\\n"; else cout << "\n\n"; *report << "This plan has the following further condition(s) to check:"; if(LaTeX) *report << "\\\\\n\\\\\n"; else cout << "\n\n"; pr.getValidator().displayInvariantWarnings(); }; if(pr.getValidator().graphsToShow()) showGraphs = true; cout << pet; } catch(exception & e) { if(LaTeX) { *report << "\\error \\\\\n"; *report << "\\end{tabbing}\n"; *report << "Error occurred in validation attempt:\\\\\n " << e.what() << "\n"; } else cout << "Error occurred in validation attempt:\n " << e.what() << "\n"; queries.push_back(name); }; //display error report and plan repair advice if(giveAdvice && (Verbose || ErrorReport)) { pr.firstPlanAdvice(); }; //display LaTeX graphs of PNEs if(LaTeX && showGraphs) { latex.LaTeXGraphs(&(pr.getValidator())); }; //display gantt chart of plan if(LaTeX) { latex.LaTeXGantt(&(pr.getValidator())); }; planNoTimedLits->clear(); delete planNoTimedLits; delete the_plan; }; if(!rnk.empty()) { if(LaTeX) { *report << "\\section{Successful Plans}\n"; } else if(!Silent) cout << "\nSuccessful plans:"; if(current_analysis->the_problem->metric && current_analysis->the_problem->metric->opt == E_MINIMIZE) { if(LaTeX) { *report << "\\begin{tabbing}\n"; *report << "{\\bf Value} \\qquad \\= {\\bf Plan}\\\\[0.8ex]\n"; }; if(!Silent && !LaTeX) for_each(rnk.begin(),rnk.end(),showList()); if(LaTeX) *report << "\\end{tabbing}\n"; } else { if(LaTeX) { *report << "\\begin{tabbing}\n"; *report << "{\\bf Value} \\qquad \\= {\\bf Plan}\\\\[0.8ex]\n"; }; if(!Silent && !LaTeX) for_each(rnk.rbegin(),rnk.rend(),showList()); if(LaTeX) *report << "\\end{tabbing}\n"; }; *report << "\n"; }; if(!rnkInv.empty()) { if(LaTeX) { *report << "\\section{Successful Plans Subject To Further Checks}\n"; } else if(!Silent) cout << "\nSuccessful Plans Subject To Further Invariant Checks:"; if(current_analysis->the_problem->metric && current_analysis->the_problem->metric->opt == E_MINIMIZE) { if(LaTeX) { *report << "\\begin{tabbing}\n"; *report << "{\\bf Value} \\qquad \\= {\\bf Plan}\\\\[0.8ex]\n"; }; for_each(rnkInv.begin(),rnkInv.end(),showList()); if(LaTeX) *report << "\\end{tabbing}\n"; } else { if(LaTeX) { *report << "\\begin{tabbing}\n"; *report << "{\\bf Value} \\qquad \\= {\\bf Plan}\\\\[0.8ex]\n"; }; for_each(rnkInv.rbegin(),rnkInv.rend(),showList()); if(LaTeX) *report << "\\end{tabbing}\n"; }; *report << "\n"; }; if(!failed.empty()) { if(LaTeX) { *report << "\\section{Failed Plans}\n"; } else cout << "\n\nFailed plans:\n "; if(LaTeX) displayFailedLaTeXList(failed); else copy(failed.begin(),failed.end(),ostream_iterator<string>(cout," ")); *report << "\n"; }; if(!queries.empty()) { if(LaTeX) { *report << "\\section{Queries (validator failed)}\n"; } else cout << "\n\nQueries (validator failed):\n "; if(LaTeX) displayFailedLaTeXList(queries); else copy(queries.begin(),queries.end(),ostream_iterator<string>(cout," ")); *report << "\n"; }; };
/////////////////////////////////////////////////////////////////////////////////////////////////////////// //functions for colMatrix class // //copy constructor colMatrix::colMatrix( const colMatrix &cp){ (*this).size = cp.Size(); (*this).data = new double[cp.Size()]; copy(&cp.data[0], &cp.data[0] + cp.Size(), &(*this).data[0]); }
void MatMulCheck(string TestFile) { if (noDoubleTests<T>()) return; using std::vector; vector<af::dim4> numDims; vector<vector<T> > hData; vector<vector<T> > tests; readTests<T,T,int>(TestFile, numDims, hData, tests); af_array a, aT, b, bT; ASSERT_EQ(AF_SUCCESS, af_create_array(&a, &hData[0].front(), numDims[0].ndims(), numDims[0].get(), (af_dtype) af::dtype_traits<T>::af_type)); af::dim4 atdims = numDims[0]; { dim_t f = atdims[0]; atdims[0] = atdims[1]; atdims[1] = f; } ASSERT_EQ(AF_SUCCESS, af_moddims(&aT, a, atdims.ndims(), atdims.get())); ASSERT_EQ(AF_SUCCESS, af_create_array(&b, &hData[1].front(), numDims[1].ndims(), numDims[1].get(), (af_dtype) af::dtype_traits<T>::af_type)); af::dim4 btdims = numDims[1]; { dim_t f = btdims[0]; btdims[0] = btdims[1]; btdims[1] = f; } ASSERT_EQ(AF_SUCCESS, af_moddims(&bT, b, btdims.ndims(), btdims.get())); vector<af_array> out(tests.size(), 0); if(isBVector) { ASSERT_EQ(AF_SUCCESS, af_matmul( &out[0] , aT, b, AF_MAT_NONE, AF_MAT_NONE)); ASSERT_EQ(AF_SUCCESS, af_matmul( &out[1] , bT, a, AF_MAT_NONE, AF_MAT_NONE)); ASSERT_EQ(AF_SUCCESS, af_matmul( &out[2] , b, a, AF_MAT_TRANS, AF_MAT_NONE)); ASSERT_EQ(AF_SUCCESS, af_matmul( &out[3] , bT, aT, AF_MAT_NONE, AF_MAT_TRANS)); ASSERT_EQ(AF_SUCCESS, af_matmul( &out[4] , b, aT, AF_MAT_TRANS, AF_MAT_TRANS)); } else { ASSERT_EQ(AF_SUCCESS, af_matmul( &out[0] , a, b, AF_MAT_NONE, AF_MAT_NONE)); ASSERT_EQ(AF_SUCCESS, af_matmul( &out[1] , a, bT, AF_MAT_NONE, AF_MAT_TRANS)); ASSERT_EQ(AF_SUCCESS, af_matmul( &out[2] , a, bT, AF_MAT_TRANS, AF_MAT_NONE)); ASSERT_EQ(AF_SUCCESS, af_matmul( &out[3] , aT, bT, AF_MAT_TRANS, AF_MAT_TRANS)); } for(size_t i = 0; i < tests.size(); i++) { dim_t elems; ASSERT_EQ(AF_SUCCESS, af_get_elements(&elems, out[i])); vector<T> h_out(elems); ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void *)&h_out.front(), out[i])); if( false == equal(h_out.begin(), h_out.end(), tests[i].begin()) ) { cout << "Failed test " << i << "\nCalculated: " << endl; copy(h_out.begin(), h_out.end(), ostream_iterator<T>(cout, ", ")); cout << "Expected: " << endl; copy(tests[i].begin(), tests[i].end(), ostream_iterator<T>(cout, ", ")); FAIL(); } } ASSERT_EQ(AF_SUCCESS, af_release_array(a)); ASSERT_EQ(AF_SUCCESS, af_release_array(aT)); ASSERT_EQ(AF_SUCCESS, af_release_array(b)); ASSERT_EQ(AF_SUCCESS, af_release_array(bT)); for (size_t i = 0; i < out.size(); i++) { ASSERT_EQ(AF_SUCCESS, af_release_array(out[i])); } }
unique_ptr<multi_polygon_type> GerberImporter::render(bool fill_closed_lines, unsigned int points_per_circle) { map<int, multi_polygon_type> apertures_map; ring_type region; coordinate_type cfactor; unique_ptr<multi_polygon_type> temp_mpoly (new multi_polygon_type()); bool contour = false; vector<pair<const gerbv_layer_t *, gerberimporter_layer> >layers (1); auto layers_equivalent = [](const gerbv_layer_t * const layer1, const gerbv_layer_t * const layer2) { const gerbv_step_and_repeat_t& sr1 = layer1->stepAndRepeat; const gerbv_step_and_repeat_t& sr2 = layer2->stepAndRepeat; if (layer1->polarity == layer2->polarity && sr1.X == sr2.X && sr1.Y == sr2.Y && sr1.dist_X == sr2.dist_X && sr1.dist_Y == sr2.dist_Y) return true; else return false; }; gerbv_image_t *gerber = project->file[0]->image; if (gerber->info->polarity != GERBV_POLARITY_POSITIVE) unsupported_polarity_throw_exception(); if (gerber->netlist->state->unit == GERBV_UNIT_MM) cfactor = scale / 25.4; else cfactor = scale; layers.front().first = gerber->netlist->layer; generate_apertures_map(gerber->aperture, apertures_map, points_per_circle, cfactor); for (gerbv_net_t *currentNet = gerber->netlist; currentNet; currentNet = currentNet->next){ const point_type start (currentNet->start_x * cfactor, currentNet->start_y * cfactor); const point_type stop (currentNet->stop_x * cfactor, currentNet->stop_y * cfactor); const double * const parameters = gerber->aperture[currentNet->aperture]->parameter; multi_polygon_type mpoly; if (!layers_equivalent(currentNet->layer, layers.back().first)) { layers.resize(layers.size() + 1); layers.back().first = currentNet->layer; } map<coordinate_type, multi_linestring_type>& paths = layers.back().second.paths; unique_ptr<multi_polygon_type>& draws = layers.back().second.draws; auto merge_ring = [&](ring_type& ring) { if (ring.size() > 1) { polygon_type polygon; bg::correct(ring); if (simplify_cutins(ring, polygon)) bg::union_(*draws, polygon, *temp_mpoly); else bg::union_(*draws, ring, *temp_mpoly); ring.clear(); draws.swap(temp_mpoly); temp_mpoly->clear(); } }; auto merge_mpoly = [&](multi_polygon_type& mpoly) { bg::correct(mpoly); bg::union_(*draws, mpoly, *temp_mpoly); mpoly.clear(); draws.swap(temp_mpoly); temp_mpoly->clear(); }; if (currentNet->interpolation == GERBV_INTERPOLATION_LINEARx1) { if (currentNet->aperture_state == GERBV_APERTURE_STATE_ON) { if (contour) { if (region.empty()) bg::append(region, start); bg::append(region, stop); } else { if (gerber->aperture[currentNet->aperture]->type == GERBV_APTYPE_CIRCLE) { linestring_type new_segment; new_segment.push_back(start); new_segment.push_back(stop); merge_paths(paths[coordinate_type(gerber->aperture[currentNet->aperture]->parameter[0] * cfactor / 2)], new_segment); } else if (gerber->aperture[currentNet->aperture]->type == GERBV_APTYPE_RECTANGLE) { mpoly.resize(1); linear_draw_rectangular_aperture(start, stop, parameters[0] * cfactor, parameters[1] * cfactor, mpoly.back().outer()); merge_ring(mpoly.back().outer()); } else cerr << "Drawing with an aperture different from a circle " "or a rectangle is forbidden by the Gerber standard; skipping." << endl; } } else if (currentNet->aperture_state == GERBV_APERTURE_STATE_FLASH) { if (contour) { cerr << "D03 during contour mode is forbidden by the Gerber " "standard; skipping" << endl; } else { const auto aperture_mpoly = apertures_map.find(currentNet->aperture); if (aperture_mpoly != apertures_map.end()) bg::transform(aperture_mpoly->second, mpoly, translate(stop.x(), stop.y())); else cerr << "Macro aperture " << currentNet->aperture << " not found in macros list; skipping" << endl; merge_mpoly(mpoly); } } else if (currentNet->aperture_state == GERBV_APERTURE_STATE_OFF) { if (contour) { if (!region.empty()) { bg::append(region, stop); merge_ring(region); } } } else { cerr << "Unrecognized aperture state: skipping" << endl; } } else if (currentNet->interpolation == GERBV_INTERPOLATION_PAREA_START) { contour = true; } else if (currentNet->interpolation == GERBV_INTERPOLATION_PAREA_END) { contour = false; if (!region.empty()) merge_ring(region); } else if (currentNet->interpolation == GERBV_INTERPOLATION_CW_CIRCULAR || currentNet->interpolation == GERBV_INTERPOLATION_CCW_CIRCULAR) { if (currentNet->aperture_state == GERBV_APERTURE_STATE_ON) { const gerbv_cirseg_t * const cirseg = currentNet->cirseg; linestring_type path; if (cirseg != NULL) { double angle1; double angle2; if (currentNet->interpolation == GERBV_INTERPOLATION_CCW_CIRCULAR) { angle1 = cirseg->angle1; angle2 = cirseg->angle2; } else { angle1 = cirseg->angle2; angle2 = cirseg->angle1; } circular_arc(point_type(cirseg->cp_x * scale, cirseg->cp_y * scale), cirseg->width * scale / 2, angle1 * bg::math::pi<double>() / 180.0, angle2 * bg::math::pi<double>() / 180.0, points_per_circle, path); if (contour) { if (region.empty()) copy(path.begin(), path.end(), region.end()); else copy(path.begin() + 1, path.end(), region.end()); } else { if (gerber->aperture[currentNet->aperture]->type == GERBV_APTYPE_CIRCLE) merge_paths(paths[coordinate_type(gerber->aperture[currentNet->aperture]->parameter[0] * cfactor / 2)], path); else cerr << "Drawing an arc with an aperture different from a circle " "is forbidden by the Gerber standard; skipping." << endl; } } else cerr << "Circular arc requested but cirseg == NULL" << endl; } else if (currentNet->aperture_state == GERBV_APERTURE_STATE_FLASH) { cerr << "D03 during circular arc mode is forbidden by the Gerber " "standard; skipping" << endl; } } else if (currentNet->interpolation == GERBV_INTERPOLATION_x10 || currentNet->interpolation == GERBV_INTERPOLATION_LINEARx01 || currentNet->interpolation == GERBV_INTERPOLATION_LINEARx001 ) { cerr << "Linear zoomed interpolation modes are not supported " "(are them in the RS274X standard?)" << endl; } else //if (currentNet->interpolation != GERBV_INTERPOLATION_DELETED) { cerr << "Unrecognized interpolation mode" << endl; } } for (pair<const gerbv_layer_t *, gerberimporter_layer>& layer : layers) { for (pair<const coordinate_type, multi_linestring_type>& path : layer.second.paths) { simplify_paths(path.second); } } return generate_layers(layers, fill_closed_lines, cfactor, points_per_circle); }
bool llvm::returnTypeIsEligibleForTailCall(const Function *F, const Instruction *I, const ReturnInst *Ret, const TargetLoweringBase &TLI) { // If the block ends with a void return or unreachable, it doesn't matter // what the call's return type is. if (!Ret || Ret->getNumOperands() == 0) return true; // If the return value is undef, it doesn't matter what the call's // return type is. if (isa<UndefValue>(Ret->getOperand(0))) return true; // Make sure the attributes attached to each return are compatible. AttrBuilder CallerAttrs(F->getAttributes(), AttributeSet::ReturnIndex); AttrBuilder CalleeAttrs(cast<CallInst>(I)->getAttributes(), AttributeSet::ReturnIndex); // Noalias is completely benign as far as calling convention goes, it // shouldn't affect whether the call is a tail call. CallerAttrs = CallerAttrs.removeAttribute(Attribute::NoAlias); CalleeAttrs = CalleeAttrs.removeAttribute(Attribute::NoAlias); bool AllowDifferingSizes = true; if (CallerAttrs.contains(Attribute::ZExt)) { if (!CalleeAttrs.contains(Attribute::ZExt)) return false; AllowDifferingSizes = false; CallerAttrs.removeAttribute(Attribute::ZExt); CalleeAttrs.removeAttribute(Attribute::ZExt); } else if (CallerAttrs.contains(Attribute::SExt)) { if (!CalleeAttrs.contains(Attribute::SExt)) return false; AllowDifferingSizes = false; CallerAttrs.removeAttribute(Attribute::SExt); CalleeAttrs.removeAttribute(Attribute::SExt); } // If they're still different, there's some facet we don't understand // (currently only "inreg", but in future who knows). It may be OK but the // only safe option is to reject the tail call. if (CallerAttrs != CalleeAttrs) return false; const Value *RetVal = Ret->getOperand(0), *CallVal = I; SmallVector<unsigned, 4> RetPath, CallPath; SmallVector<CompositeType *, 4> RetSubTypes, CallSubTypes; bool RetEmpty = !firstRealType(RetVal->getType(), RetSubTypes, RetPath); bool CallEmpty = !firstRealType(CallVal->getType(), CallSubTypes, CallPath); // Nothing's actually returned, it doesn't matter what the callee put there // it's a valid tail call. if (RetEmpty) return true; // Iterate pairwise through each of the value types making up the tail call // and the corresponding return. For each one we want to know whether it's // essentially going directly from the tail call to the ret, via operations // that end up not generating any code. // // We allow a certain amount of covariance here. For example it's permitted // for the tail call to define more bits than the ret actually cares about // (e.g. via a truncate). do { if (CallEmpty) { // We've exhausted the values produced by the tail call instruction, the // rest are essentially undef. The type doesn't really matter, but we need // *something*. Type *SlotType = RetSubTypes.back()->getTypeAtIndex(RetPath.back()); CallVal = UndefValue::get(SlotType); } // The manipulations performed when we're looking through an insertvalue or // an extractvalue would happen at the front of the RetPath list, so since // we have to copy it anyway it's more efficient to create a reversed copy. using std::copy; SmallVector<unsigned, 4> TmpRetPath, TmpCallPath; copy(RetPath.rbegin(), RetPath.rend(), std::back_inserter(TmpRetPath)); copy(CallPath.rbegin(), CallPath.rend(), std::back_inserter(TmpCallPath)); // Finally, we can check whether the value produced by the tail call at this // index is compatible with the value we return. if (!slotOnlyDiscardsData(RetVal, CallVal, TmpRetPath, TmpCallPath, AllowDifferingSizes, TLI)) return false; CallEmpty = !nextRealType(CallSubTypes, CallPath); } while(nextRealType(RetSubTypes, RetPath)); return true; }
int main(int argc, char *argv[]) { #if defined(macintosh) argc = ccommand(&argv); #endif if (flagOption(argc,argv,"--help") || flagOption(argc,argv,"--pete-help")) { cout << "gen_operators produces global functions for C++\n"; cout << "operators (+ - * etc.) that create expression trees.\n"; cout << "Global assignment operators may be produced as well.\n"; cout << "This function can also produce operator tag structs.\n\n"; cout << "Options:\n"; cout << "--help: Print this message.\n"; cout << "--pete-help: Print this message.\n"; cout << "--classes file: Read the class descriptors from file.\n"; cout << " If no class file is provided, then\n"; cout << " no operators or assignment operators\n"; cout << " are produced.\n"; cout << "--o file: Name of file to write operator info to.\n"; cout << " If not specified, output goes to the\n"; cout << " terminal.\n"; cout << "--operators file: Read the operator descriptors from\n"; cout << " file.\n"; cout << " If no operator file is provided, then\n"; cout << " the standard set of PETE operators is\n"; cout << " used (most of the C++ operators).\n"; cout << "--pete-ops: Add the set of PETE operators to those\n"; cout << " input from the operator file.\n"; cout << "--guard string: Use string for the include guard\n"; cout << " (defaults to GENERATED_OPERATORS_H).\n"; cout << "--scalars: If this flag is present, only generate\n"; cout << " operators involving user-defined scalars."; cout << "--extra-classes: If this flag is present, only generate\n"; cout << " operators involving the extraClasses.\n"; cout << "--no-expression: If this flag is present, don't generate\n"; cout << " operators involving Expression<T>\n"; cout << "--assign-ops: If this flag is present, generate the\n"; cout << " assignment operators that call\n"; cout << " evaluate().\n"; cout << "--op-tags: If this flag is present, generate the\n"; cout << " operator tag structs\n"; cout << "--no-shift-guard: If this flag is present, put no guards\n"; cout << " around the scalar << class and \n"; cout << " scalar >> class operators (they can\n"; cout << " get confused with stream operations).\n\n"; cout << "These two options are used internally by PETE:\n"; cout << "--insert-op: Used to build the file\n"; cout << " src/tools/PeteOps.cpp.\n"; // cout << "--lanl-boilerplate: Includes the standard ACL header and\n"; // cout << " footer." << endl; return 0; } vector<string> filesUsed; filesUsed.push_back("gen_operators"); bool printOperators = flagOption(argc,argv,"--classes"); string cls = stringOption(argc,argv,"--classes",""); string ofile = stringOption(argc, argv, "--o", ""); string guardDef(printOperators ? "GENERATED_OPERATORS_H" : "OPERATOR_TAGS_H"); string includeGuard = stringOption(argc,argv,"--guard",guardDef); bool justScalars = flagOption(argc,argv,"--scalars"); bool justExtraClasses = flagOption(argc,argv,"--extra-classes"); bool expression = !flagOption(argc,argv,"--no-expression"); bool assignment = flagOption(argc,argv,"--assign-ops"); bool printTags = flagOption(argc,argv,"--op-tags"); bool shiftGuard = !flagOption(argc,argv,"--no-shift-guard"); bool insertOp = flagOption(argc,argv,"--insert-op"); bool addPeteOps = (!flagOption(argc,argv,"--operators")) || flagOption(argc,argv,"--pete-ops"); // bool lanlBoilerplate = flagOption(argc,argv,"--lanl-boilerplate"); string prefix, suffix; // Input the operator descriptors. map<string, vector<OperatorDescriptor> > mOps; map<string, vector<OperatorDescriptor> > inputOps; if (flagOption(argc,argv,"--operators")) { string ops = stringOption(argc,argv,"--operators",""); ifstream fOps(ops.c_str()); filesUsed.push_back(ops); PInsist1(!!fOps, "ERROR: couldn't open operator description file \"" "%s\"", ops.c_str()); Parser<OperatorDescriptor> pOps(fOps, ops, mOps); pOps.addKeyword("TAG"); pOps.addKeyword("FUNCTION"); pOps.addKeyword("EXPR"); pOps.addKeyword("ARG"); pOps.addKeyword("STREXPR"); pOps.parse(); prefix = pOps.prefixText(); suffix = pOps.suffixText(); } inputOps = mOps; //// XXX //vector<OperatorDescriptor> tmp(mOps["unaryOps"]); //for(int i=0; i< tmp.size(); i++) std::cout<<tmp[i]; if (addPeteOps) { peteOps(mOps); } // Create vectors for unary operators. vector<OperatorDescriptor> unaryOps(mOps["unaryOps"]); copy(mOps["unaryBoolOps"].begin(), mOps["unaryBoolOps"].end(), back_inserter(unaryOps)); copy(mOps["unarySpecialOps"].begin(), mOps["unarySpecialOps"].end(), back_inserter(unaryOps)); vector<OperatorDescriptor> &unaryCastOps = mOps["unaryCastOps"]; // Create vectors for binary operators. vector<OperatorDescriptor> binaryOps(mOps["binaryOps"]); copy(mOps["binaryBoolOps"].begin(), mOps["binaryBoolOps"].end(), back_inserter(binaryOps)); // copy(mOps["binaryLeftOps"].begin(), mOps["binaryLeftOps"].end(), // back_inserter(binaryOps)); copy(mOps["binarySpecialOps"].begin(), mOps["binarySpecialOps"].end(), back_inserter(binaryOps)); vector<OperatorDescriptor> binaryLeftOps(mOps["binaryLeftOps"]); // Create reference for trinary operators. vector<OperatorDescriptor> &trinaryOps = mOps["trinaryOps"]; // Create vector for assignment operators. vector<OperatorDescriptor> assignOps(mOps["assignOp"]); copy(mOps["binaryAssignOps"].begin(), mOps["binaryAssignOps"].end(), back_inserter(assignOps)); copy(mOps["binaryAssignBoolOps"].begin(), mOps["binaryAssignBoolOps"].end(), back_inserter(assignOps)); // Input the class descriptors. map<string, vector<ClassDescriptor> > mClasses; vector<ClassDescriptor> classes; vector<ClassDescriptor> extraClasses; vector<ClassDescriptor> scalars; vector<ClassDescriptor> generalT; vector<ClassDescriptor> userClasses; vector<ClassDescriptor> expressionClass; if (printOperators) { ifstream fClasses(cls.c_str()); filesUsed.push_back(cls); if (justScalars) { filesUsed.push_back("(Only operations with scalars were printed.)"); } PInsist1(!!fClasses, "ERROR: couldn't open class description file \"" "%s\"", cls.c_str()); Parser<ClassDescriptor> pClasses(fClasses, cls, mClasses); pClasses.addKeyword("ARG"); pClasses.addKeyword("CLASS"); pClasses.parse(); if (prefix.size() != 0) prefix += "\n\n"; if (suffix.size() != 0) suffix += "\n\n"; prefix += pClasses.prefixText(); suffix += pClasses.suffixText(); classes = mClasses["classes"]; extraClasses = mClasses["extraClasses"]; scalars = mClasses["scalars"]; userClasses = classes; if (expression) { expressionClass.push_back(ClassDescriptor("class T[n]", "Expression<T[n]>")); classes.push_back(ClassDescriptor("class T[n]", "Expression<T[n]>")); } if (!justScalars) { scalars.push_back(ClassDescriptor("class T[n]","T[n]")); } } generalT.push_back(ClassDescriptor("class T[n]","T[n]")); // Set up streams for printing. ostream *ofl = &cout; if (ofile != string("")) { ofl = new ofstream(ofile.c_str()); PInsist1(ofl != NULL, "ERROR: couldn't open class description file \"" "%s\"", ofile.c_str()); PInsist1(!!*ofl, "ERROR: couldn't open class description file \"" "%s\"", ofile.c_str()); } // Print header. printHeader(*ofl,includeGuard,filesUsed,lanlBoilerplate,prefix); // The following code is used when we generate PeteOps.cpp from // PeteOps.in. Users should never use the --insert-ops option. if (insertOp) { *ofl << "#include \"OperatorDescriptor.h\"" << endl << "#include <vector>" << endl << "#include <map>" << endl << "#include <string>" << endl << "using std::map;" << endl << "using std::vector;" << endl << "using std::string;" << endl << endl; *ofl << endl << "void peteOps(map<string," << "vector<OperatorDescriptor> > &m)" << endl << "{" << endl; map<string,vector<OperatorDescriptor> >::iterator opvec; for(opvec = mOps.begin();opvec != mOps.end();++opvec) { printList(*ofl,InsertOp(opvec->first),opvec->second); } *ofl << "}" << endl; } // Print operator tags. if (printTags) { printList(*ofl,UnaryOp(), inputOps["unaryOps"]); printList(*ofl,UnaryBoolOp(), inputOps["unaryBoolOps"]); printList(*ofl,UnaryCastOp(), inputOps["unaryCastOps"]); printList(*ofl,UnarySpecialOp(), inputOps["unarySpecialOps"]); printList(*ofl,BinaryOp(), inputOps["binaryOps"]); printList(*ofl,BinaryBoolOp(), inputOps["binaryBoolOps"]); printList(*ofl,BinaryLeftOp(), inputOps["binaryLeftOps"]); printList(*ofl,BinarySpecialOp(), inputOps["binarySpecialOps"]); printList(*ofl,BinaryAssignOp(), inputOps["binaryAssignOps"]); printList(*ofl,BinaryAssignOp(), inputOps["assignOp"]); printList(*ofl,BinaryAssignBoolOp(),inputOps["binaryAssignBoolOps"]); printList(*ofl,TrinaryOp(), inputOps["trinaryOps"]); } // Print operators. if (printOperators) { if (!justScalars) { if (!justExtraClasses) { printList(*ofl,UnaryFunction(),unaryOps,userClasses); printList(*ofl,UnaryCastFunction(),unaryCastOps,userClasses); printList(*ofl,BinaryFunction(),binaryOps,userClasses,userClasses); printList(*ofl,BinaryFunction(),binaryLeftOps,userClasses,userClasses); printList(*ofl,BinaryFunction(),binaryOps, userClasses, expressionClass); printList(*ofl,BinaryFunction(),binaryLeftOps, userClasses, expressionClass); printList(*ofl,BinaryFunction(),binaryOps, expressionClass, userClasses); printList(*ofl,BinaryFunction(),binaryLeftOps, expressionClass, userClasses); } else { printList(*ofl,UnaryFunction(),unaryOps,extraClasses); printList(*ofl,UnaryCastFunction(),unaryCastOps,extraClasses); printList(*ofl,BinaryFunction(),binaryOps,extraClasses,extraClasses); printList(*ofl,BinaryFunction(),binaryLeftOps,extraClasses, extraClasses); printList(*ofl,BinaryFunction(),binaryOps,classes,extraClasses); printList(*ofl,BinaryFunction(),binaryLeftOps,classes,extraClasses); printList(*ofl,BinaryFunction(),binaryOps,extraClasses,classes); printList(*ofl,BinaryFunction(),binaryLeftOps,extraClasses,classes); } } if (!justExtraClasses) { printList(*ofl,BinaryFunction(),binaryOps,userClasses,scalars); printList(*ofl,BinaryFunction(),binaryLeftOps,userClasses,scalars); printList(*ofl,BinaryFunction(),binaryOps,scalars,userClasses); } else { printList(*ofl,BinaryFunction(),binaryOps,extraClasses,scalars); printList(*ofl,BinaryFunction(),binaryLeftOps,extraClasses,scalars); printList(*ofl,BinaryFunction(),binaryOps,scalars,extraClasses); } // The following flag covers the common situation where you define // ostream << class. Some compilers define cout to be a class that // inherits from ostream, so the compiler would use the PETE shift // operators T << class which defines shift for scalars and the user // class. Since this shift operration is pretty bizzare, and stream // output is pretty common, the default behaviour of PETE is to turn // off the operators that allow for scalar << container and // scalar << expression. if (shiftGuard) { *ofl << "#ifdef PETE_ALLOW_SCALAR_SHIFT" << endl; } if (!justExtraClasses) { printList(*ofl,BinaryFunction(),binaryLeftOps,scalars,userClasses); } else { printList(*ofl,BinaryFunction(),binaryLeftOps,scalars,extraClasses); } if (shiftGuard) { *ofl << "#endif // PETE_ALLOW_SCALAR_SHIFT" << endl; } if (!justScalars) { if (!justExtraClasses) { printList(*ofl,TrinaryFunction(),trinaryOps,userClasses, generalT,generalT); } else { printList(*ofl,TrinaryFunction(),trinaryOps,extraClasses,generalT, generalT); } } // Operators involving expression are guarded to make it easy to combine // operator files for different classes. It's possible to generate // files that you can combine by using --no-expression for one of them, but // this approach is simpler. Thanks to J. Striegnitz, // Research Center Juelich for coming up with this approach. if (expression) { *ofl << "#ifndef PETE_EXPRESSION_OPERATORS" << endl; *ofl << "#define PETE_EXPRESSION_OPERATORS" << endl; if (printOperators) { if (!justScalars) { if (!justExtraClasses) { printList(*ofl,UnaryFunction(),unaryOps,expressionClass); printList(*ofl,UnaryCastFunction(),unaryCastOps,expressionClass); printList(*ofl,BinaryFunction(),binaryOps, expressionClass, expressionClass); printList(*ofl,BinaryFunction(),binaryLeftOps, expressionClass, expressionClass); } } if (!justExtraClasses) { printList(*ofl,BinaryFunction(),binaryOps,expressionClass,scalars); printList(*ofl,BinaryFunction(),binaryLeftOps, expressionClass, scalars); printList(*ofl,BinaryFunction(),binaryOps,scalars,expressionClass); } if (shiftGuard) { *ofl << "#ifdef PETE_ALLOW_SCALAR_SHIFT" << endl; } if (!justExtraClasses) { printList(*ofl,BinaryFunction(),binaryLeftOps,scalars, expressionClass); } if (shiftGuard) { *ofl << "#endif // PETE_ALLOW_SCALAR_SHIFT" << endl; } if (!justScalars) { if (!justExtraClasses) { printList(*ofl,TrinaryFunction(),trinaryOps,expressionClass, generalT,generalT); } } } *ofl << "#endif // PETE_EXPRESSION_OPERATORS" << endl; } } // Print assignment operators. if (assignment) { if (!justExtraClasses) { printList(*ofl,AssignFunctionForClass(),assignOps,userClasses); } else { printList(*ofl,AssignFunctionForClass(),assignOps,extraClasses); } } // Print footer. printFooter(*ofl,includeGuard,lanlBoilerplate,suffix); // Clean up. if (ofile != string("")) delete ofl; }
/*! * Constructs Vector from std::initializaer list * \param l list of initial values for vector */ Vector(std::initializer_list<T> l) : m_size(l.size()), m_capacity(m_size), m_data(new T[m_size]) { copy(l.begin(), l.end(), m_data); }