chi*_*llu 1 c++ templates traits
我已经定义在C++,其保持型的标量的阵列的类T为其中我想要定义像正弦,余弦等运营商为了限定的含义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)
}
Run Code Online (Sandbox Code Playgroud)
目前,我有代码公开适当的数学库(使用命名空间std;),然后::sin(a)在我的类的sin函数内使用MyType.虽然这有效,但它似乎是一个重大的黑客.
我看到,C++性状可以被用来存储实例特定的信息(例如其中的数学函数组使用时T是double,当T是BigNum,等.)
我想做这样的事情:(我知道这不会编译,但我希望这传达了我想做的事)
template<T>
struct MyType_traits {
};
template<>
struct MyType_traits<double> {
namespace math = std;
};
template<>
struct MyType_traits<BigNum> {
namespace math = somelib::bigtype;
};
Run Code Online (Sandbox Code Playgroud)
然后重新定义我的MyType类:
template<T, traits = MyType_traits<T> >
class MyType
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
然后traits::math::sin在我的朋友功能中使用.有没有办法可以获得T包含数学函数的正确命名空间(参数化)?
依赖于参数的查找不够好吗?
#include <cmath>
#include <iostream>
namespace xxx {
class X
{
};
X sin(X) { return X(); }
} //xxx
std::ostream& operator<< (std::ostream& os, xxx::X)
{
return os << "X";
}
template <class T>
void use_sin(T t)
{
using std::sin; //primitive types are not in a namespace,
//and with some implementation sin(double) etc might not be available
//in global namespace
std::cout << sin(t) << '\n';
}
int main()
{
use_sin(1.0);
use_sin(xxx::X());
}
Run Code Online (Sandbox Code Playgroud)
这适用于X,因为sin(X)它在与X相同的命名空间中定义.如果你不希望如此,这可能无济于事......