用函数重载,实现两个不同类型数据的相加,包括int型,float型,double型,一维和二维数组;编写主函数对重载函数进行测试 (考虑是否可以同时用函数模板)
谢谢!
下面代码需要打开C++17编译选项。
#include <iostream>
#include <iomanip>
template <typename T>
void add(T &a, T b, T c)
{
a = b + c;
}
template <typename T, int N>
void add(T (&a)[N], const T (&b)[N], const T (&c)[N])
{
for (int i = 0; i < N; i++)
a[i] = b[i] + c[i];
}
template <typename T, int M, int N>
void add(T (&a)[M][N], const T (&b)[M][N], const T (&c)[M][N])
{
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
a[i][j] = b[i][j] + c[i][j];
}
template <typename T, int N>
std::enable_if_t<!std::is_same_v<std::remove_cv_t<T>, char>, std::ostream &>
operator<<(std::ostream &os, const T (&a)[N])
{
os << '[';
for (int i = 0; i < N; i++)
{
os << std::setw(2) << a[i];
if (i < N - 1)
os << ' ';
}
os << ']';
return os;
}
template <typename T, int M, int N>
std::enable_if_t<!std::is_same_v<std::remove_cv_t<T>, char>, std::ostream &>
operator<<(std::ostream &os, const T (&a)[M][N])
{
for (int i = 0; i < M; i++)
{
os << '[';
for (int j = 0; j < N; j++)
{
os << std::setw(3) << a[i][j];
if (i < N - 1)
os << ' ';
}
os << "]\n";
}
return os;
}
#define TEST1(type, x, y) \
do \
{ \
type a, b = x, c = y; \
add(a, b, c); \
std::cout << std::setw(6) << #type << ": " << b << " + " << c << " = " << a << std::endl; \
} while (0)
#define TEST2(type, N) \
do \
{ \
type a[N], b[N], c[N]; \
for (int i = 0; i < N; i++) \
{ \
b[i] = i; \
c[i] = i * 2; \
} \
add(a, b, c); \
std::cout << std::setw(6) << #type << ": " << b << " + " << c << " = " << a << std::endl; \
} while (0)
#define TEST3(type, M, N) \
do \
{ \
type a[M][N], b[M][N], c[M][N], k = 0; \
for (int i = 0; i < M; i++) \
{ \
for (int j = 0; j < N; j++) \
{ \
b[i][j] = k++; \
c[i][j] = k * 2; \
} \
} \
add(a, b, c); \
std::cout << std::setw(6) << #type << ":\n" \
<< b << "+\n" \
<< c << "=\n" \
<< a << std::endl; \
} while (0)
int main()
{
TEST1(int, 1, 2);
TEST1(float, 1, 2);
TEST1(double, 1, 2);
TEST2(int, 5);
TEST2(float, 5);
TEST2(double, 5);
TEST3(int, 3, 5);
TEST3(float, 3, 5);
TEST3(double, 3, 5);
return 0;
}
$ g++ -Wall -std=c++17 main.cpp
$ ./a.out
int: 1 + 2 = 3
float: 1 + 2 = 3
double: 1 + 2 = 3
int: [ 0 1 2 3 4] + [ 0 2 4 6 8] = [ 0 3 6 9 12]
float: [ 0 1 2 3 4] + [ 0 2 4 6 8] = [ 0 3 6 9 12]
double: [ 0 1 2 3 4] + [ 0 2 4 6 8] = [ 0 3 6 9 12]
int:
[ 0 1 2 3 4 ]
[ 5 6 7 8 9 ]
[ 10 11 12 13 14 ]
+
[ 2 4 6 8 10 ]
[ 12 14 16 18 20 ]
[ 22 24 26 28 30 ]
=
[ 2 5 8 11 14 ]
[ 17 20 23 26 29 ]
[ 32 35 38 41 44 ]
float:
[ 0 1 2 3 4 ]
[ 5 6 7 8 9 ]
[ 10 11 12 13 14 ]
+
[ 2 4 6 8 10 ]
[ 12 14 16 18 20 ]
[ 22 24 26 28 30 ]
=
[ 2 5 8 11 14 ]
[ 17 20 23 26 29 ]
[ 32 35 38 41 44 ]
double:
[ 0 1 2 3 4 ]
[ 5 6 7 8 9 ]
[ 10 11 12 13 14 ]
+
[ 2 4 6 8 10 ]
[ 12 14 16 18 20 ]
[ 22 24 26 28 30 ]
=
[ 2 5 8 11 14 ]
[ 17 20 23 26 29 ]
[ 32 35 38 41 44 ]