![](/img/trans.png)
[英]template function to handle different array dimensions and data types in c++
[英]c++ pass multiple data types (including arrays of different dimensions) to function
我正在嘗試創建一個可以處理張量的 class。 在 function 的構造函數中,我想傳遞不同數據類型(int,vectors ...)的輸入。 我還想通過 arrays 總是具有不同的尺寸(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);
}
這實際上是完整的 class:
// 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};
}
Output:
arithmetic::itegral::unsigned
arithmetic::itegral::signed
arithmetic::floating_point
array with extent 10
無需對您的 class 將提供什么以及在此處使用模板是否有意義提出太多問題,您可以使用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 {
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.