Down Caste a class

Hello guys .
I have my class vector as follow:
1
2
3
4
5
6
7
8
9
10
11
12
13
template <class T>
class vector
{
public:
	vector(){vector(0,0,0);};
        vector(T ,T ,T );
        friend ostream& operator<< <> (ostream& output,vector<T>& );
	template <class U>
        vector<T> plus(const vector<U>& vec);
//private:////
    T x,y,z;
};

the class can only be double or int .
i am not sure how to check that , i tried if T==double but apparently it doesnt work.
I also have my plus function takes two vectors assuming one is double one is in
it only works if T is double and U is int or both int or both double.
But what if U is double and T is int this is also a problem that i am having .
I hope someone can help
Thanks
Ok, two solutions. One defeats the purpose of templates, the other is extremely advanced.

Solution one. Specialize the template for int and double. Means writing the full implementation for double and int, defeating the purpose of the template.

Solution two. Use some boost::mpl (m4ster r0shi, you out there? :))

EDIT: line 5 does not do what you want.
Last edited on
FYI, the topic was a little misleading. This had nothing to do with downcasting =P

Anyway, if you need to know the type of T, it's generally a sign that you're doing things wrong. The idea of templates is that they'll work with any type. If you're writing functions that will only work with specific types, then templates don't really do anything for you.

That said... I'm not entirely sure I understand your problem.

But what if U is double and T is int this is also a problem that i am having .


I see no reason why your plus function wouldn't work in that situation. Other than that you'd lose precision when you convert int to double.
Hi,
Thank you for your fast reply .
I need my class to only take int or double , i understand now that template class is not a good idea for that . Not sure how it suppose to be then.
closed account (1yR4jE8b)
Just a side note, you probably shouldn't name your class vector because that could reek havoc if you need to include std::vector and you also using namespace std:


1
2
3
4
5
6
7
8
9
10
#include <vector>
#include "vector.h"
using namespace std;

int main()
{
     vector<int> myVector;     //KABLAM, compiler doesn't know which vector to use....

     return 0;
}


You could solve this by either: putting your vector in it's own namespace, or renaming your class to say Vector.

Just a tip. Naming user-defined classes after standard-library and STL classes is definitely not a good idea ;-P
Yah the use of this project is to replace the normal vector class , I am planning to do what you said . thanks for the advice , still stuck at the same problem
Topic archived. No new replies allowed.