[英]How to use Structs in Templates as Parameters c++
前幾天我在 c++ 中看到了一個關於模板的視頻,它有以下代碼:
template <typename T>
void someFunction(T num) {
Print(num);
}
“Print()”只是在控制台中打印出 var “num”。 我基本上了解了如何使用模板作為參數。 但是,我不知道如何將它與 Structs 一起使用,或者是否有可能。 我的意思是這樣的:
struct vec2 {
float x, y;
};
struct vec3 {
float x, y, z;
};
template <typename T>
void someFunction(T vec);
我想在 function 中檢查“vec”是 vec2 還是 vec3,然后以不同的方式使用它。 像這樣:
if (vec==vec2) {
//Print x and y
else if (vec==vec3) {
//Print x, y and z
}
最后,我的目標只是擁有一個 function ,我可以提供 2 個不同的結構。 我已經聽說過 std::is_same 並嘗試過,但沒有任何成功。
這實際上可以使用類型特征和if constexpr
:
#include <iostream>
#include <type_traits>
struct vec2 {
float x, y;
};
struct vec3 {
float x, y, z;
};
template <typename T>
void someFunction(T vec)
{
if constexpr (std::is_same_v<T, vec2>) {
std::cout << vec.x << ' ' << vec.y << '\n';
}
else if constexpr (std::is_same_v<T, vec3>) {
std::cout << vec.x << ' ' << vec.y << ' ' << vec.z << '\n';
}
}
int main()
{
vec2 v2 = {1, 2};
vec3 v3 = {3, 4, 5};
someFunction(v2);
someFunction(v3);
}
(注意在 C++17 之前,您需要std::is_same<T, vec2>::value
。)
話雖如此,在您的示例中,一組簡單的 function 重載會更合適:
#include <iostream>
struct vec2 {
float x, y;
};
struct vec3 {
float x, y, z;
};
void someFunction(vec2 vec) {
std::cout << vec.x << ' ' << vec.y << '\n';
}
void someFunction(vec3 vec) {
std::cout << vec.x << ' ' << vec.y << ' ' << vec.z << '\n';
}
int main()
{
vec2 v2 = {1, 2};
vec3 v3 = {3, 4, 5};
someFunction(v2);
someFunction(v3);
}
在這兩種情況下,您可能希望考慮通過 const 引用而不是通過值(這將復制它)來獲取 object。
Asteroids With Wings 的答案給出了兩個解決方案,而其中的第二個可能就是你想要的。 但第一個絕對不是; 您只需使用 function 模板專業化即可實現相同的功能:
#include <iostream>
struct vec2 {
float x, y;
};
struct vec3 {
float x, y, z;
};
template <typename T>
void someFunction(T vec) ;
template<>
void someFunction<>(vec2 vec)
{
std::cout << vec.x << ' ' << vec.y << '\n';
}
template<>
void someFunction<>(vec3 vec)
{
std::cout << vec.x << ' ' << vec.y << ' ' << vec.z << '\n';
}
int main()
{
vec2 v2 = {1, 2};
vec3 v3 = {3, 4, 5};
someFunction(v2);
someFunction(v3);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.