bpw1621
bpw1621

Reputation: 3062

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

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.

Upvotes: 5

Views: 232

Answers (4)

Nicol Bolas
Nicol Bolas

Reputation: 474376

This was on the long list of things for C++0x. It's why they created this odd function definition format:

auto FuncName(Type1 param1, Type2 param2) -> ReturnType {...}

It, combined with decltype, allows you to do things like this:

auto FuncName(Type1 param1, Type2 param2) -> decltype(param1 + param2) {...}

This means that the return type will be whatever you get when you call operator+(Type1, Type2).

Note that C++ is a statically typed language. You cannot do type computations at runtime. It must be done at compile time, via mechanisms like this or some form of template metaprogramming.

Upvotes: 0

Node
Node

Reputation: 3509

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.

Upvotes: 11

Marc B
Marc B

Reputation: 360872

Pardon my horrible C, since it's been forever since I actually worked with it:

typedef int RandomVariable;
typedef float RandomVariableCovariance;

RandomVariableCovariance myFunc(RandomVariable x) {
    ....
}

Upvotes: -2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272762

Typenames cannot be parameters or return values of a function; types are a compile-time thing!

Upvotes: 2

Related Questions