AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79224009
Accepted
pacmaninbw
pacmaninbw
Asked: 2024-11-26 01:13:05 +0800 CST2024-11-26 01:13:05 +0800 CST 2024-11-26 01:13:05 +0800 CST

Faça com que estruturas semelhantes sejam conversíveis em C++20 ou C++23

  • 772

Estou tentando obter um construtor que aceite intervalos, sejam vetores ou matrizes de uma estrutura definida pelo usuário.

Estou usando std::convertible_to<>

A mensagem de erro do compilador é onde eu chamo o construtor.

`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>

Como faço para TestDataPairme tornar conversível para DictType?

DicionárioGenérico.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;
}

Conjunto completo de mensagens de erro

[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.
c++
  • 1 1 respostas
  • 91 Views

1 respostas

  • Voted
  1. Best Answer
    LHLaurini
    2024-11-26T01:33:24+08:002024-11-26T01:33:24+08:00

    Como TestDataPaire GenericDictionary<TestFunctionalityEnumDict, std::string>::DictTypesão idênticos, não há razão para que sejam tipos diferentes.

    Como tal, você pode simplesmente substituir

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

    com

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

    Para completar:

    Usando uma função de conversão definida pelo usuário

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

    Usando Boost.PFR (exagero):

    #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>)) {
        }
    
    // [...]
    };
    

    Usando ligações estruturadas:

    // 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;
        };
    
    // [...]
    };
    

    Quando P1061 estiver disponível, podemos tornar nossa função auxiliar válida para qualquer número de membros:

    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); };
    

    Claro, isso também pode ser usado para substituir Boost.PFR no exemplo anterior.

    • 4

relate perguntas

  • Por que os compiladores perdem a vetorização aqui?

  • Erro de compilação usando CMake com biblioteca [fechada]

  • Erro lançado toda vez que tento executar o premake

  • Como criar um tipo de octeto semelhante a std::byte em C++?

  • Somente operações bit a bit para std::byte em C++ 17?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle?

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Quando devo usar um std::inplace_vector em vez de um std::vector?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Martin Hope
    Aleksandr Dubinsky Por que a correspondência de padrões com o switch no InetAddress falha com 'não cobre todos os valores de entrada possíveis'? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer Quando devo usar um std::inplace_vector em vez de um std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB Por que o GCC gera código que executa condicionalmente uma implementação SIMD? 2024-02-17 06:17:14 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve