I have defined a class in C++ which holds an array of scalars of type T
for which I want to define operators like sin, cos, etc. For defining the meaning of sin
applied on an object of this class I need to know the meaning of sin
applied on the single scalar type T
. This means I need to use appropriate math libraries (corresponding to the scalar type T
) within the class. Here's the code as it is now:
template<class T>
class MyType<T>
{
private:
std::vector<T> list;
// ...
template<class U> friend const UTP<U> sin(const UTP<U>& a);
template<class U> friend const UTP<U> cos(const UTP<U>& a);
template<class U> friend const UTP<U> tan(const UTP<U>& a);
//...
};
template<class T> const UTP<T> sin(const UTP<T>& a)
{
// use the sin(..) appropriate for type T here
// if T were double I want to use double std::sin(double)
// if T were BigNum I want to use BigNum somelib::bigtype::sin(BigNum)
}
Currently, I have code that exposes the appropriate math library (using namespace std;) and then use ::sin(a)
inside the sin function for my class MyType
. While this works, it seems like a major hack.
I see that C++ traits can be used to store instance specific information (like which set of math functions to use when T
is double
, when T
is BigNum
, etc..)
I want to do something like this: (I know this doesn't compile but I hope this conveys what I want to do)
template<T>
struct MyType_traits {
};
template<>
struct MyType_traits<double> {
namespace math = std;
};
template<>
struct MyType_traits<BigNum> {
namespace math = somelib::bigtype;
};
and then in redefine my MyType class as:
template<T, traits = MyType_traits<T> >
class MyType
{
// ...
}
and then use traits::math::sin
in my friend function. Is there a way in which I can obtain the correct namespace (parameterized by T
) containing the math functions?