我在 C++ 中定义了一个类,它包含一个类型的标量数组T
,我想为其定义诸如 sin、cos 等运算符。为了定义sin
应用于此类的对象的含义,我需要知道sin
应用于的含义单一的标量类型T
。这意味着我需要在T
类中使用适当的数学库(对应于标量类型)。这是现在的代码:
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)
}
目前,我的代码公开了适当的数学库(使用命名空间 std;),然后::sin(a)
在我的类的 sin 函数中使用MyType
。虽然这有效,但它似乎是一个重大的黑客攻击。
我看到 C++ 特征可用于存储实例特定信息(例如使用哪组数学函数 when T
is double
, when T
isBigNum
等)
我想做这样的事情:(我知道这不会编译,但我希望这能传达我想要做的事情)
template<T>
struct MyType_traits {
};
template<>
struct MyType_traits<double> {
namespace math = std;
};
template<>
struct MyType_traits<BigNum> {
namespace math = somelib::bigtype;
};
然后将我的 MyType 类重新定义为:
template<T, traits = MyType_traits<T> >
class MyType
{
// ...
}
然后traits::math::sin
在我的朋友功能中使用。有没有一种方法可以获得T
包含数学函数的正确命名空间(由 参数化)?