gpt4 book ai didi

c++ - 根据模板参数(C++ 特性?)使用不同的函数集

转载 作者:行者123 更新时间:2023-11-30 01:31:14 24 4
gpt4 key购买 nike

我在 C++ 中定义了一个类,它包含一个类型为 T 的标量数组,我想为其定义诸如 sin、cos 等运算符。用于定义 sin< 的含义 应用于此类的对象 我需要了解应用于单个标量类型 Tsin 的含义。这意味着我需要在类中使用适当的数学库(对应于标量类型 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;),然后在我的类 MyType 的 sin 函数中使用 ::sin(a) >。虽然这可行,但它似乎是一个重大的黑客攻击。

我看到 C++ 特征可用于存储实例特定信息(例如当 Tdouble 时使用哪组数学函数,当 TBigNum 等。)

我想做这样的事情:(我知道这不能编译,但我希望这传达了我想做的事情)

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 参数化)?

最佳答案

依赖参数的查找还不够好吗?

#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());
}

这适用于 X,因为 sin(X) 是在与 X 相同的命名空间中定义的。如果您认为情况并非如此,那么这可能无济于事...

关于c++ - 根据模板参数(C++ 特性?)使用不同的函数集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3431704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com