C++: How to enable std::apply for user-define class? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 2

C++: How to enable std::apply for user-define class?

I found in the reference that std::apply works not only with std::tuple, but also with other types like std::pair and std::array which support std::tuple_size and std::get. https://en.cppreference.com/w/cpp/utility/apply This made me wonder if I can enable std::apply for a class by overloading std::tuple_size and std::get for them. I tried doing this (I hope the code is clear enough, feel free to point out if it isn't) https://code.sololearn.com/c87G8s5r04U0/?ref=app For some reason, the std::get implementation provided by me for `Container` isn't even considered by the compiler. 1. Is what I'm trying to do possible? 2. If yes, then what am I doing wrong?

14th May 2021, 2:49 PM
XXX
XXX - avatar
2 Antworten
+ 1
Doesn't extending stl leads to undefined behaviour ?
14th May 2021, 4:12 PM
Arsenic
Arsenic - avatar
+ 1
Arsenic Well, I didn't know that. From https://en.cppreference.com/w/cpp/language/extending_std: "It is allowed to add template specializations for any standard library class template to the namespace std only if the declaration depends on at least one program-defined type and the specialization satisfies all requirements for the original template, except where such specializations are prohibited." So I guess my specialization for std::tuple_size is fine "It is undefined behavior to declare a full specialization of any standard library function template." Does this mean my overload for std::get is not allowed? That might explain why the compiler does not consider that overload. So is it safe to conclude that this is the reason? I still find it weird though that I can still call the std::get overload and it works fine. But it doesn't work when used in std::apply. I mean, this works fine `std::cout << std::get<1>( Container<A, B, C>{} );` Thanks for your help
14th May 2021, 5:49 PM
XXX
XXX - avatar