I tried to get CTAD to work with std::map
, but I can not get it to work.
#include<iostream>
#include<string>
#include<map>
#include<vector>
using namespace std;
using namespace std::string_literals;
int main() {
std::vector v{1,2,3}; // ok
std::map m{{4, "four"s},{7,"seven"s},{1,"one"s},{5,"five"s}}; // error
}
Is there a way to make it work, or is std::map
to complicated for it to work?
Class Template Argument Deduction (CTAD) is a C++17 Core Language feature that reduces code verbosity. C++17's Standard Library also supports CTAD, so after upgrading your toolset, you can take advantage of this new feature when using STL types like std::pair and std::vector.
Yes, a std::map<K,V> is ordered based on the key, K , using std::less<K> to compare objects, by default.
std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare . Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees.
Alex April 24, 2022, 7:49 pm August 24, 2022. Class template argument deduction (CTAD) C++17. Starting in C++17, when instantiating an object from a class template, the compiler can deduce the template types from the types of the object's initializer (this is called class template argument deduction or CTAD for short).
The problem is that this std::map m{{4, "four"s},{7,"seven"s},{1,"one"s},{5,"five"s}}; // error
is an {}
of {}
s, and CTAD doesn't do that.
If you do std::map m{std::pair{4, "four"s},{7,"seven"s},{1,"one"s},{5,"five"s}};
it becomes an initializer list, which CTAD works on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With