Skip to content

Instantly share code, notes, and snippets.

@sdkfz181tiger
Last active May 15, 2024 06:31
Show Gist options
  • Save sdkfz181tiger/21696b529129bbb18e3dbd8e47b39e09 to your computer and use it in GitHub Desktop.
Save sdkfz181tiger/21696b529129bbb18e3dbd8e47b39e09 to your computer and use it in GitHub Desktop.
C/C++課題ネタ06_関数テンプレート、クラステンプレート
//==========
// テンプレート(関数テンプレート)
// 1, Compile
// g++ -std=c++17 -Wall -Wextra main.cpp
// 2, Run
// ./a.out
#include <math.h>
#include <stdio.h>
template <typename T>
T add(const T& a, const T& b){
return a + b;
}
int main(){
// Test
const int numA = add<int>(1, 2);
printf("numA: %d\n", numA);
const float numB = add<float>(1.0f, 2.0f);
printf("numB: %f\n", numB);
const double numC = add<double>(1.0, 2.0);
printf("numC: %f\n", numC);
return 0;
}
//==========
// テンプレート(クラステンプレート)
// 1, Compile
// g++ -std=c++17 -Wall -Wextra main.cpp
// 2, Run
// ./a.out
#include <math.h>
#include <stdio.h>
template <typename T>
class Vec2{
public:
const T x;
const T y;
Vec2(T x, T y): x(x),y(y){}
};
int main(){
const Vec2<int> vecA(1, 2);
const Vec2<float> vecB(1.0f, 2.0f);
printf("vecA: %d, %d\n", vecA.x, vecA.y);
printf("vecB: %f, %f\n", vecB.x, vecB.y);
return 0;
}
//==========
// テンプレート(クラステンプレート+演算子オーバーライド)
// 1, Compile
// g++ -std=c++17 -Wall -Wextra main.cpp
// 2, Run
// ./a.out
#include <math.h>
#include <stdio.h>
template <typename T>
class Vec2{
public:
const T x;
const T y;
Vec2(T x, T y): x(x),y(y){}
Vec2 operator+(const Vec2 &rhs) const{
return Vec2(x+rhs.x, y+rhs.y);
}
Vec2 operator-(const Vec2 &rhs) const{
return Vec2(x-rhs.x, y+rhs.y);
}
};
int main(){
const Vec2<int> vecA(1, 2);
const Vec2<int> vecB(3, 4);
const Vec2<int> vecC = vecA + vecB;
printf("vecC: %d, %d\n", vecC.x, vecC.y);
const Vec2<int> vecD = vecC + vecA + vecB;
printf("vecD: %d, %d\n", vecD.x, vecD.y);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment