Some examples about CTAD

CTAD is Class Template Argument Deduction in C++17. With CTAD, we can write so-called deduction guides to tell the compiler how to instantiate a class template. Thanks to CTAD, class templates can look more like function templates. There we usually don’t have to state the types other than passing the parameters. The compiler then derives the types from these parameters.

CTAD in std::vector

1
2
3
4
// Before
std::vector<int> v{1, 2, 3};
// After
std::vector v{1, 2, 3};

CTAD in array

1
2
3
4
5
6
7
8
9
10
11
12
#include <cstddef>

template<typename T, size_t N>
struct array {
T data[N];
};

// A Deduction guide
template<typename T, typename... Args>
array(T, Args...) -> array<T, 1 + sizeof...(Args)>;

array a0{1, 2, 3, 4, 5};

Custom CTAD

1

1
2
3
4
5
6
7
8
9
template <typename T>
struct ReturnCode {
T value;
};
// Guide compiler to deduct the type in template argument list
template <typename T>
ReturnCode(T) -> ReturnCode<T>;

ReturnCode return_code{1};

2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
#include <variant>

using namespace std::literals;

template <typename... Ts>
struct Overload : Ts... {
using Ts::operator()...;
};

template <typename... Ts>
Overload(Ts&&...) -> Overload<Ts...>;

int main() {
std::variant<int, std::string> variant{"Hello World"s};
std::visit(Overload{[](const int& i) {
std::cout << i << std::endl;
},
[](const std::string& s) {
std::cout << s << std::endl;
}},
variant);

return 0;
}

References


Some examples about CTAD
http://wasprime.github.io/Dev/C++/Miscellaneous/Some-examples-about-CTAD/
Author
wasPrime
Posted on
May 12, 2023
Updated on
May 11, 2023
Licensed under