Some Template Meta Programming Practices

A discovery

I found a case that struck me.

1
2
3
4
5
6
7
8
9
10
template <class T>
struct temp {
T value;
};

template <class T, class... Ts>
struct temp {
temp<T> value_temp;
temp<Ts...> rest_temps;
};

It can’t pass compiling with a error message - Too many template parameters in template redeclaration.

It would work if we changed it as below:

1
2
3
4
5
6
7
8
9
10
11
12
13
template <class T, class... Ts>
struct temp;

template <class T>
struct temp<T> {
T value;
};

template <class T, class... Ts>
struct temp {
temp<T> value_temp;
temp<Ts...> rest_temps;
};

The declaration with multiple parameters certainly can be placed at the beginning, as long as you like. :)

Accumulate the parameters in the template

I wrote the below code to practice template specialization.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

template <int i, int... Args>
struct Sum {
static constexpr int value = i + Sum<Args...>::value;
};

template <int i>
struct Sum<i> {
static constexpr int value = i;
};

int main() {
std::cout << Sum<1, 2, 3>::value << std::endl;
return 0;
}

Minimum value

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

template <int i, int... args>
struct Min {
private:
static constexpr int tmp = Min<args...>::value;

public:
static constexpr int value = i < tmp ? i : tmp;
};

template <int i>
struct Min<i> {
static constexpr int value = i;
};

int main() {
std::cout << Min<1, 2, 3>::value << std::endl;
return 0;
}

Some Template Meta Programming Practices
http://wasprime.github.io/Dev/C++/template/Some-Template-Meta-Programming-Practices/
Author
wasPrime
Posted on
April 6, 2023
Updated on
May 11, 2023
Licensed under