C++ Logo

std-proposals

Advanced search

Re: A new proposal, new key-word definition for dynamic, run-time type-cast operations

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Tue, 13 Jul 2021 16:22:56 -0400
Hi Jerry,
>From your code sample, it looks like you're trying to reinvent a technique
known in C++ as "type erasure."
In today's C++, that would look like this:

#include "unique_printable.h" // see
https://quuxplusone.github.io/blog/2020/11/24/type-erased-printable/

struct arrItem {
    int key;
    UniquePrintable item1;
    UniquePrintable item2;
};

int main()
{
    std::vector<arrItem> DataList;
    DataList.push_back({ 0, 101, 102.10 });
    DataList.push_back({ 1, 201, 202 });
    DataList.push_back({ 2, 301, "hello world" }); // just for fun
    for (auto& [key, item1, item2] : DataList) {
        std::cout << "key: " << key << "; item1: " << item1 << "; item2: "
<< item2 << "\n";
    }
}

Here is the C++17 code all worked out, and executing correctly, on Godbolt.
https://godbolt.org/z/bdPTT7oeo <https://godbolt.org/z/jxzs6Exso>

I've omitted any equivalent of your `Example_1` and `Example_2` wrappers,
because I didn't think they were important to the technique you were trying
to show. But you can certainly see how to re-introduce them if you need to;
and how to use type erasure for operations other than simple printing, as
well.
See also "Back to Basics: Type Erasure" (CppCon 2019):
https://www.youtube.com/watch?v=tbUCHifyT24

HTH,
Arthur


On Tue, Jul 13, 2021 at 8:46 AM Jaroslav Moravec via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> New proposal, version 2.
>
> Abstract
>
> The C++ language is here for more that 36 years and is still under
> development. Sometimes, C++ borrows some ideas from other programming
> languages, sometimes works on its own way. Presented proposal try to
> introduce a new type of basic variable which would be capable to hold a
> type of a variable or a type of a class or a struct. This variable should
> be capable to define target new type in type-cast operations such us:
> static_cast or dynamic_cast etc. Both at running time and at compilation
> time. Type of a variable or a class/struct is usually given by its unique
> name. Thus, the new basic variable should contain a string – the name of
> basic datatype or a type of user defined datatype. This name is then used
> in the type-cast operation at running time. The target type is, of course,
> well known at compilation time.
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2021-07-13 15:23:09