How to use RTTI to determine the behavior of code
I have a piece of code to use the RTTI as case selector
#include <iostream>
#include <vector>
#include <typeinfo>
#include <complex>
#include <algorithm>
using namespace std;
typedef complex<int> data;
typedef std::vector< data > List;
template <typename T> void zeros(T &v)
{
if (typeid(typename T::value_type)==typeid(complex<int>))
std::fill(v.begin(), v.end(), complex<int>(0, 0));
else std::fill(v.begin(), v.end(), static_cast<typename T::value_type>(0));
}
int main(int argc, char *argv[])
{
List A;
zeros(A);
return 0;
}
In above code, I use typename T::value_type to determine the data type of
the list, if there is complex then I will fill the list with complex zero.
Otherwise, make it zero of the corresponding type. In above code, if I set
data to be int, it does compile and run without any problem. But if I set
it another other type, it fail to compile. I wonder if there is any way to
make above code work for different type of data (for float, double, long,
int, complex, complex and complex).
p.s. the reason I want to fill the vector in two cases because I am going
to create my own complex for some reason and I have to tell the code how
to create the complex zero or real zero. But for testing, I can't even
make it work with built-in datatype
No comments:
Post a Comment