By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,505 Members | 1,761 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,505 IT Pros & Developers. It's quick & easy.

How to do this? (Template selection?)

P: n/a
I have a function which needs to return different values but that takes
no arguments, this is the function:

template <class T>
T funct();

For each type T for different types, there are different ways of
calculating the return value. To implement this, I've done the
following (for example):

void _internal_funct(int &val) {val = 42;}
void _internal_funct(double &val) {val = 3.141592;}

template <class T>
T funct()
{
T val;
_internal_funct(val);
return val;
}

This works reasonably well (though does anyone know a better way to do
this?). My only problem is I want to have a default return value for
anything I do not explicitly define (such as returning 0 for all
pointer types, and a compiler error for classes).

If I used a pointer instead of a reference I might have been able to
use an elipse, but it would make the first two definitions of
_internal_funct ambiguous:

void _internal_funct(...) { *[get a void pointer] = 0; }

---

More specifically, my ultimate goal is something like this:
// calculates a value and returns it based off of internalStateObject1
int i = funct<int>(internalStateObject1);

// calculates a bool and returns it based off of internalStateObject2
bool b = funct<bool>(internalStateObject2); // calculates a bool and
returns it

// calculates a pointer to a SomeClass object based off of
internalStateObject3
SomeClass *class = funct<SomeClass *>(internalStateObject3);

// compiler error or undefined behavior
SomeClass class2 = funct<SomeClass>(internalStateObject4);

Is this even possible in C++, or should I try to do this with something
other than template magic? I'm trying to make this easy for someone
using the function, even if it makes the implementation more complex.

Nov 22 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.