Jump to content
  • Advertisement
Sign in to follow this  
ndwork

Type promotion

This topic is 3453 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a templated container class. I would like to be able to add this class to a literal value, as follows: cout << 2 + container<double> << endl; So I've created an operator + function that looks like:
template< class T >
container<T> operator +( const T &value, const container<T> &in ){
   return in + T;
}
I can create a conversion constructor that converts a container of type S to a container of type T. Thus, the above line will compile (I think). The problem is that I would like to preserve the more specific type. For example, in the case where I'm adding 2 (an int) to a container of type double, I would like the result to be a container of type double. Is there a way to make this happen?

Share this post


Link to post
Share on other sites
Advertisement
As it is 2 + container<double> wouldn't compile since typeof(2) needs to be the same as double. You'd have to explicitly cast one or the other to the desired type.

If you were to use two different template arguments then some time ago a discussion about a vector class turned into a discussion how to promote the result of vector<T1> + vector<T2> into a suitable type. (Or how to select T1 or T2 based on which should be promoted to the other. I don't think a perfect solution was reached there but you can get close.)

Share this post


Link to post
Share on other sites
You could just use two template parameters to make sure that the return value is always the exact container type. Ex:

template <typename T, typename U>
std::vector<T> operator+(const std::vector<T> & lhs, const U & rhs) {
std::vector<T> copy(lhs);
copy.push_back(rhs);
return copy;
}

template <typename T, typename U>
std::vector<T> operator+(const U & lhs, const std::vector<T> & rhs) {
std::vector<T> copy(rhs);
copy.push_back(lhs);
return copy;
}

int main(int, char **) {
std::vector<double> container;
std::vector<double> c1 = container + 2;
std::vector<double> c2 = 2 + container;

return 0;
}


However, this is a pretty inefficient way to deal with containers.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!