給定以下矢量類(用於2d,3d或4d矢量數學),它使用std :: array,是否可以定義可變參數和/或轉換構造函數?可變的用戶定義的轉換/構造函數
作爲後續的問題,這種事情是不好的做法?我發現自己需要轉換爲整數,浮點數和雙精度。
我知道隱式轉換會發生,但我的編譯器會給我警告(我不想一般關閉它們)。
#include <array>
template<typename T0, size_t S>
class Vec
{
public:
static_assert(S > 1 && S < 5, "vector dimension must be between 2 and 4");
static_assert(std::is_arithmetic<T0>::value, "type must be arithmetic");
std::array<T0, S> v;
Vec() = default;
template<class T1, class T2>
Vec(T1 t1, T2 t2) : v({ static_cast<T0>(t1),
static_cast<T0>(t2) }) {}
template<class T1, class T2, class T3>
Vec(T1 t1, T2 t2, T3 t3) : v({ static_cast<T0>(t1),
static_cast<T0>(t2),
static_cast<T0>(t3) }) {}
template<class T1, class T2, class T3, class T4>
Vec(T1 t1, T2 t2, T3 t3, T4 t4) : v({ static_cast<T0>(t1),
static_cast<T0>(t2),
static_cast<T0>(t3),
static_cast<T0>(t4) }) {}
};
int main(void)
{
auto foo1 = Vec<float, 2>(1, 2);
auto foo2 = Vec<float, 2>(1.0f, 2.0f);
auto foo3 = Vec<float, 2>(1.0, 2.0);
auto foo4 = Vec<float, 2>(1u, 2u);
return 0;
}
您對模板參數S靜態斷言似乎很奇怪。如果它必須大於1且小於3,那麼你可以說它一定是2. – antred
謝謝。修復。 2,3或4. – Robinson