I want to write a function that calls several sub functions and return the result of these sub functions.
sub functions:
template<class A> A sub1(A a)
template<class B> B sub2(B b, int i)
template<class C> C sub3(C c, string p)
THE function will call these accordingly in the switch statement.
Sorry I only have pseudo code since I am confused with the issue and not start to write the code.
mf(string s)
{
int k;
k = process(s)
string
switch (k){
case 0:
return sub1(k);
case 1:
return sub2(s, k);
case 2:
return sub3(k, s);
default:
break;
}
}
How can I define mf above since there is no return type for it now? using template again?
By the way, my c++ compiler does support c++ 11 standard which I am not so familiar with.
C++ is basically a static-typed language, which means all types of expressions are decided at compile time rather than at run time.
Using dynamic-typing in a static-typed language is possible, but not recommended for widely use. Because doing so you’re giving up almost all the polymorphism features provided by the language. You’ll have to check types manually, or implement your own dynamic-type-based polymorphism.
If the data returned is not too complex, tagged structure is usually a good idea:
For more complex data types with a lot of operations needed to support, you should consider using abstract interfaces and inheritance.
If you considered the problem seriously and believe that none of those methods above applies to your problem, and that dynamic typing is the best way, here are some options:
boost::any— A unique container for all types. Need to test for types and convert them manually before use.boost::variant— A union-like container which supports unary polymorphic operations viaboost::static_visitor.Some programming frameworks have their own support for dynamic-typing. One example is
QVariantin Qt. If you are in such a framework, it’s usually recommended to use them instead of something else from another library.