i trying create function in c++, wondering if can create such able return different types of vectors. e.g based on different case returns vector string, int, double or ...anything. possible in c++? (i not want use overload function different arg(s) , different returns) new c++ , question may seem stupid.
here piece of code:
//zero here means intersection
std::vector<??????> findzeros(const mesh::region& s, char *model) const { //point if( model == "point" ) { std::vector<vertex> zeros; for(region::pointiterator = s.beginpoint(); itv != s.endpoint(); ++itv ) { if( abs(val(*it)) < 1.e-12 ) zeros.push_back(*it); } std::vector<point> zerosp(zeros.begin(), zeros.end()); return zerosp; } //line else if (entitys == "line") { std::vector<line> zerose; std::vector<point&> pointe; for(region::lineiterator ite = s.beginline(); ite != s.endline(); ++ite ) { line ed = *ite; point p0 = ed.point(0); point p1 = e.point(1); if( ......... ) zerose.push_back(ed); else if ( ....... ) { ponte.push_back( p0, p1); zerose.push_back(ed); } }
//here want return "point" or "line points" or in upper level our surface. //i want in 1 function! }
templates
try this:
template <typename t> std::vector<t> func( /* arguments */ ) { std::vector<t> v; // ... stuff vector ... return v; }
you can call function different type in way:
std::vector<int> func<int>( args ); std::vector<double> func<double>( args );
alternatives
this 1 way, if know types @ compile-time. if don't know type @ compile-time @ run-time only, have different choices:
- use
unions
. can recommend this, if have simple c-struct-like types called pods (plain old data) in c++ standard. - use type of variant. example there
boost::variant
boost libraries orqvariant
qt library. safe kind of unions on more general types. allow conversions between different types. example setting integer value make possible read same value floating point number. - use
boost::any
can wrap type not allow conversions between them. - use inheritance , polymorphism. case need common base class,
base
. create array of pointers base preferablystd::shared_ptrs
. array typestd::vector<std::shared_ptr<base>>
.std::shared_ptr
better built in pointers in case because manage memory automagically reference counting. - use dynamic language doesn't care types , performance.
Comments
Post a Comment