如何解决c++ 将多种数据类型包括不同维度的数组传递给函数
我正在尝试创建一个可以处理张量的类。在函数的构造函数中,我想传递不同数据类型(int、vectors...)的输入。我还想传递始终具有不同维度(1D、3D...)的数组。对于构造函数,我想出了这样的事情:
template <class T>
Tensor(T input) {
// ...
}
但是,我应该如何获取传递的 dtype 以便处理输入? 我希望是这样的:
if (isInt(input)) {
} else if (isFloat(input)) {
} /* and so on for vectors,strings etc... */ {
} else if (isArray(input)) {
int dim = getDimension(input);
}
这实际上是完整的课程:
// Take `Tensor` template parameters,defining its
// content data type. Use `float32` as default.
template <class D = float64>
// Define Tensor class.
class Tensor {
public:
// Define class constructor.
template <class T>
Tensor(T input) {
using content_dtype = D;
}
};
解决方法
您可以使用 constexpr-if:
#include <iostream>
#include <type_traits>
template <class D = double>
class Tensor {
public:
using content_dtype = D; // put it here for everyone to see
template <class T>
Tensor(const T& input) {
if constexpr (std::is_arithmetic_v<T>) {
if constexpr (std::is_integral_v<T>) {
if constexpr (std::is_unsigned_v<T>) {
std::cout << "arithmetic::itegral::unsigned\n";
} else {
std::cout << "arithmetic::itegral::signed\n";
}
} else {
std::cout << "arithmetic::floating_point\n";
}
} else if constexpr (std::is_array_v<T>) {
auto dim = std::extent_v<T>;
std::cout << "array with extent " << dim << '\n';
}
}
};
int main() {
unsigned a;
int b;
double c;
int d[10];
Tensor A{a};
Tensor B{b};
Tensor C{c};
Tensor D{d};
}
输出:
arithmetic::itegral::unsigned
arithmetic::itegral::signed
arithmetic::floating_point
array with extent 10
,
无需过多询问您的类将提供什么以及在此处使用模板是否有意义,您可以使用 if constexpr
将您想到的内容转换为可用的 C++17 代码:
if constexpr (std::is_integral_v<T>) {
...
} else if constexpr (std::is_floating_point_v<T>) {
...
}
现在对于像 std::vector
这样的类型,你必须想出你自己的特征:
template <typename T>
struct is_vector : std::false_type {
};
template <typename... Args>
struct is_vector<std::vector<Args...>> : std::true_type {
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。