c++templatesc++20std-rangesc++23

Make similar structs be convertible in C++20 or C++23


I'm trying to get a constructor that accepts ranges, either vectors or arrays of a user defined struct.

I'm using std::convertible_to<>

The compiler error message is where I call the constructor.

`GenericDictionary<TestFunctionalityEnumDict, std::string> dictionary(testPostivePathVec);`
./SO_Minimize_Code/unitTests/ptp_vector.cpp: In function ‘int main()’:
./SO_Minimize_Code/unitTests/ptp_vector.cpp:27:92: error: no matching function for call to ‘GenericDictionary<TestFunctionalityEnumDict, std::__cxx11::basic_string<char>

How do I get TestDataPair to be convertable to DictType?

GenericDictionary.h

#ifndef GENERICDICTIONARY_H_
#define GENERICDICTIONARY_H_

#include <concepts>
#include <ranges>
#include <string>
#include <vector>

template <typename DictID, typename DictName>
class GenericDictionary
{
public:
    struct DictType
    {
        DictID id;
        DictName names;
    };

    template<std::ranges::input_range R>
    requires std::convertible_to<std::ranges::range_reference_t<R>, DictType>
    GenericDictionary(R&& definitions)
    : userInputList{std::ranges::begin(definitions), std::ranges::end(definitions)}
    {
    }
    virtual ~GenericDictionary() = default;

private:

    std::vector<DictType> userInputList;
};

#endif // GENERICDICTIONARY_H_
#include "GenericDictionary.h"
#include <string>
#include <vector>

enum class TestFunctionalityEnumDict
{
    FunctionalTest_0,
    FunctionalTest_1,
    FunctionalTest_2
};

struct TestDataPair
{
    TestFunctionalityEnumDict id;
    std::string names;
};

std::vector<TestDataPair> testPostivePathVec = 
{
    {TestFunctionalityEnumDict::FunctionalTest_0, "Functional Test Str 0"},
    {TestFunctionalityEnumDict::FunctionalTest_1, "Functional Test Str 1"},
    {TestFunctionalityEnumDict::FunctionalTest_2, "Functional Test Str 2"}
};

int main()
{
    GenericDictionary<TestFunctionalityEnumDict, std::string> dictionary(testPostivePathVec);
    
    return EXIT_SUCCESS;
}

Full Set of Error Messages

[1/2] Building CXX object unitTests/CMakeFiles/ptp_vector.dir/ptp_vector.cpp.o
FAILED: unitTests/CMakeFiles/ptp_vector.dir/ptp_vector.cpp.o 
/usr/bin/g++-12  -I./SO_Minimize_Code/. -I./SO_Minimize_Code/./unitTests -Wall -Wextra -pedantic -fprofile-arcs -ftest-coverage -g -std=gnu++23 -Werror -MD -MT unitTests/CMakeFiles/ptp_vector.dir/ptp_vector.cpp.o -MF unitTests/CMakeFiles/ptp_vector.dir/ptp_vector.cpp.o.d -o unitTests/CMakeFiles/ptp_vector.dir/ptp_vector.cpp.o -c ./SO_Minimize_Code/unitTests/ptp_vector.cpp
./SO_Minimize_Code/unitTests/ptp_vector.cpp: In function ‘int main()’:
./SO_Minimize_Code/unitTests/ptp_vector.cpp:27:92: error: no matching function for call to ‘GenericDictionary<TestFunctionalityEnumDict, std::__cxx11::basic_string<char> >::GenericDictionary(std::vector<TestDataPair>&)’
   27 |     GenericDictionary<TestFunctionalityEnumDict, std::string> dictionary(testPostivePathVec);
      |                                                                                            ^
In file included from ./SO_Minimize_Code/unitTests/ptp_vector.cpp:1:
./SO_Minimize_Code/./GenericDictionary.h:21:5: note: candidate: ‘template<class R>  requires (input_range<R>) && (convertible_to<typename std::__detail::__iter_traits_impl<typename std::remove_cvref<decltype(std::ranges::__cust_access::__begin((declval<_Range&>)()))>::type, std::indirectly_readable_traits<typename std::remove_cvref<decltype(std::ranges::__cust_access::__begin((declval<_Range&>)()))>::type> >::__iter_traits<typename std::remove_cvref<decltype(std::ranges::__cust_access::__begin((declval<_Range&>)()))>::type, std::indirectly_readable_traits<typename std::remove_cvref<decltype(std::ranges::__cust_access::__begin((declval<_Range&>)()))>::type> >::value_type, GenericDictionary<DictID, DictName>::DictType>) GenericDictionary<DictID, DictName>::GenericDictionary(R&&) [with DictID = TestFunctionalityEnumDict; DictName = std::__cxx11::basic_string<char>]’
   21 |     GenericDictionary(R&& definitions)
      |     ^~~~~~~~~~~~~~~~~
./SO_Minimize_Code/./GenericDictionary.h:21:5: note:   template argument deduction/substitution failed:
./SO_Minimize_Code/./GenericDictionary.h:21:5: note: constraints not satisfied
In file included from ./SO_Minimize_Code/./GenericDictionary.h:4:
/usr/include/c++/12/concepts: In substitution of ‘template<class R>  requires (input_range<R>) && (convertible_to<typename std::__detail::__iter_traits_impl<typename std::remove_cvref<decltype(std::ranges::__cust_access::__begin((declval<_Range&>)()))>::type, std::indirectly_readable_traits<typename std::remove_cvref<decltype(std::ranges::__cust_access::__begin((declval<_Range&>)()))>::type> >::__iter_traits<typename std::remove_cvref<decltype(std::ranges::__cust_access::__begin((declval<_Range&>)()))>::type, std::indirectly_readable_traits<typename std::remove_cvref<decltype(std::ranges::__cust_access::__begin((declval<_Range&>)()))>::type> >::value_type, GenericDictionary<DictID, DictName>::DictType>) GenericDictionary<TestFunctionalityEnumDict, std::__cxx11::basic_string<char> >::GenericDictionary(R&&) [with R = TestFunctionalityEnumDict]’:
./SO_Minimize_Code/unitTests/ptp_vector.cpp:27:92:   required from here
/usr/include/c++/12/concepts:72:13:   required for the satisfaction of ‘convertible_to<std::ranges::range_value_t<_Range>, GenericDictionary<DictID, DictName>::DictType>’ [with R = std::vector<TestDataPair, std::allocator<TestDataPair> >&; DictID = TestFunctionalityEnumDict; DictName = std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >]
/usr/include/c++/12/concepts:72:30: note: the expression ‘is_convertible_v<_From, _To> [with _From = TestDataPair; _To = GenericDictionary<TestFunctionalityEnumDict, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >::DictType]’ evaluated to ‘false’
   72 |     concept convertible_to = is_convertible_v<_From, _To>
      |                              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
./SO_Minimize_Code/./GenericDictionary.h:10:7: note: candidate: ‘constexpr GenericDictionary<TestFunctionalityEnumDict, std::__cxx11::basic_string<char> >::GenericDictionary(const GenericDictionary<TestFunctionalityEnumDict, std::__cxx11::basic_string<char> >&)’
   10 | class GenericDictionary
      |       ^~~~~~~~~~~~~~~~~
./SO_Minimize_Code/./GenericDictionary.h:10:7: note:   no known conversion for argument 1 from ‘std::vector<TestDataPair>’ to ‘const GenericDictionary<TestFunctionalityEnumDict, std::__cxx11::basic_string<char> >&’
ninja: build stopped: subcommand failed.

Solution

  • As TestDataPair and GenericDictionary<TestFunctionalityEnumDict, std::string>::DictType are identical, there is no reason for them to be different types.

    As such, you can simply replace

    struct TestDataPair
    {
        TestFunctionalityEnumDict id;
        std::string names;
    };
    

    with

    using TestDataPair = GenericDictionary<TestFunctionalityEnumDict, std::string>::DictType;
    

    For completeness:

    Using an user-defined conversion function

    struct TestDataPair
    {
        TestFunctionalityEnumDict id;
        std::string names;
    
        operator GenericDictionary<TestFunctionalityEnumDict, std::string>::DictType() const
        {
            return { .id = id, .names = names };
        }
    };
    

    Using Boost.PFR (overkill):

    #include <boost/pfr/core.hpp>
    
    template <typename T, typename U>
    concept PFRConvertibleTo = requires(const T& t, const U& u) {
        requires std::convertible_to<decltype(boost::pfr::structure_tie(t)),
                                     decltype(boost::pfr::structure_tie(u))>;
    };
    
    template <typename To>
    constexpr auto convert_from_similar =
        [](const PFRConvertibleTo<To> auto& from) {
            To result;
            boost::pfr::structure_tie(result) = boost::pfr::structure_tie(from);
            return result;
        };
    
    template <typename DictID, typename DictName>
    class GenericDictionary {
    // [...]
    
        template <std::ranges::input_range R>
            requires std::convertible_to<std::ranges::range_reference_t<R>,
                                         DictType>
        GenericDictionary(R&& definitions)
            : userInputList{std::ranges::begin(definitions),
                            std::ranges::end(definitions)} {}
    
        template <std::ranges::input_range R>
            requires(
                !std::convertible_to<std::ranges::range_reference_t<R>, DictType> &&
                PFRConvertibleTo<std::ranges::range_reference_t<R>, DictType>)
        GenericDictionary(R&& definitions)
            : GenericDictionary(definitions | std::views::transform(
                                                  convert_from_similar<DictType>)) {
        }
    
    // [...]
    };
    

    Using structured bindings:

    // Will only work for structs with 2 members
    template <typename T, typename Other>
    static auto make_from_other_2(const Other& other) -> T {
        const auto& [first, second] = other;
        return {first, second};
    }
    
    template <typename From, typename To>
    concept MemberwiseConvertibleTo2 =
        requires(const From& from) { make_from_other_2<To, From>(from); };
    
    template <typename DictID, typename DictName>
    class GenericDictionary {
       public:
        struct DictType {
            DictType() = default;
            DictType(const DictID& id, const DictName& names)
                : id(id), names(names) {}
    
            template <MemberwiseConvertibleTo2<DictType> Other>
            DictType(const Other& other)
                : DictType(make_from_other_2<DictType, Other>(other)) {}
    
            DictID id;
            DictName names;
        };
    
    // [...]
    };
    

    Once P1061 is available we can make our helper function valid for any number of members:

    template <typename T, typename Other>
    static auto make_from_other(const Other& other) -> T {
        const auto& [...elements] = other;
        return {elements...};
    }
    
    template <typename From, typename To>
    concept MemberwiseConvertibleTo =
        requires(const From& from) { make_from_other<To, From>(from); };
    

    Of course, this can also be used to replace Boost.PFR in the previous example.