cppfront icon indicating copy to clipboard operation
cppfront copied to clipboard

[SUGGESTION] Add inspect `is()` matchers for templates

Open filipsajdak opened this issue 3 years ago • 0 comments
trafficstars

Thanks to other experiments I have added the possibility to inspect if a type is a template. That will allow generic code to check if we deal with std::vector, std::array, std::unique_ptr, std::variant, or std::initializer_list (working prototype with more templates I have checked is here: https://godbolt.org/z/ddMdq5W4T).

This change makes below code possible:

#include <vector>
#include <array>
#include <string>

template <typename A, typename B>
struct my_type {};

fun: (v : _) -> std::string = {
    return inspect v -> std::string {
        is std::vector  = "std::vector";
        is std::array   = "std::array";
        is std::variant = "std::variant";
        is my_type      = "my_type";
        is _ = "unknown";
    };
}

main: () -> int = {
    vec : std::vector<int> = (1,2,3);
    arr : std::array<int,4> = (1,2,3,4);
    var : std::variant<int, double, std::string> = ("cpp2 rulez");
    myt : my_type<int, double> = ();

    std::cout << "inspected vec : (fun(vec))$" << std::endl;
    std::cout << "inspected arr : (fun(arr))$" << std::endl;
    std::cout << "inspected var : (fun(var))$" << std::endl;
    std::cout << "inspected myt : (fun(myt))$" << std::endl;
}

Limitations

The current solution is based on template template arguments. The current solution will work with templates that match:

  • template <typename...> class C;, or
  • template <typename,auto> class C - this is needed to handle std::array

Unfortunately, there is no way of having a universal match for type and non-type parameters in a variadic way. If needed more matches there would be a need to create more combinations of template template arguments.

filipsajdak avatar Nov 04 '22 22:11 filipsajdak