Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Class template argument deduction works with std::map?

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?

like image 815
NoSenseEtAl Avatar asked May 12 '19 23:05

NoSenseEtAl


People also ask

What is template argument deduction in C++?

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.

Is std::map ordered?

Yes, a std::map<K,V> is ordered based on the key, K , using std::less<K> to compare objects, by default.

How does std::map work?

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.

What is CTAD C++?

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).


1 Answers

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.

like image 181
Yakk - Adam Nevraumont Avatar answered Sep 28 '22 10:09

Yakk - Adam Nevraumont