Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one write a function which takes a type and returns a different type

Tags:

c++

c++11

Is it possible to write a function that takes a type and returns a (related) type. For instance, a function which take a type called "RandomVariable" and return a type called "RandomVariableCovariance". I guess in general the question is whether typenames can be parameters or return types. C++0x is fine.

like image 513
bpw1621 Avatar asked Jul 04 '11 21:07

bpw1621


People also ask

Can a function return different data types?

A function can not return multiple values, but similar results can be obtained by returning an array.

Can a function return two types?

Yes if you use two different data types. For instance, consider the function given below. This would return whatever is stored in that variable a in the name of alphanumeric array. If you enter decimal, it would return decimal.

Can two functions have same name but different return type?

The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type. Save this answer.

Can a function return a type?

A function may be defined to return any type of value, except an array type or a function type; these exclusions must be handled by returning a pointer to the array or function. When a function does not return a value, void is the type specifier in the function declaration and definition.


1 Answers

You can't do it with functions, but you can do it with template specialisations. For example

template <class T>
struct ConvertType;

template <>
struct ConvertType<RandomVariable>
{
    typedef RandomVariableCovariance type;
};

int main()
{
    ConvertType<RandomVariable>::type myVar;
}

Defines a type ConvertType which is specialised to convert from RandomVariable to RandomVariableCovariance. Its possible to do all kinds of clever type selection this way depending on what you need.

like image 161
Node Avatar answered Nov 15 '22 11:11

Node