You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++20/C++23中实现相似结构体的可转换性?

解决GenericDictionary构造函数的类型转换约束问题

问题背景

尝试实现可接受range(如vector或自定义结构体数组)的GenericDictionary构造函数,使用std::convertible_to<>作为约束,但调用GenericDictionary<TestFunctionalityEnumDict, std::string> dictionary(testPostivePathVec);时出现编译错误,提示无匹配函数。需要让TestDataPair结构体可转换为GenericDictionary内部的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;
}

编译报错信息

[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.

错误原因

编译错误核心是TestDataPair无法隐式转换为GenericDictionary::DictType。尽管两个结构体的成员类型和名称完全一致,但C++将它们视为完全独立的类型,不会自动生成隐式转换规则,因此std::convertible_to<std::ranges::range_reference_t<R>, DictType>约束不满足。

解决方案

方案1:给TestDataPair添加转换运算符

在TestDataPair结构体中添加转换为目标DictType的运算符,实现隐式转换:

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

    // 隐式转换为对应GenericDictionary的DictType
    operator typename GenericDictionary<TestFunctionalityEnumDict, std::string>::DictType() const
    {
        return {id, names};
    }
};

如果需要支持通用适配(不绑定具体GenericDictionary实例化类型),可以使用模板运算符:

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

    template <typename DictID, typename DictName>
    operator typename GenericDictionary<DictID, DictName>::DictType() const
    requires std::same_as<DictID, TestFunctionalityEnumDict> && std::same_as<DictName, std::string>
    {
        return {id, names};
    }
};

方案2:给DictType添加构造函数

在GenericDictionary的DictType中添加接收TestDataPair的构造函数,允许从TestDataPair直接构造DictType:

struct DictType
{
    DictID id;
    DictName names;

    // 支持从TestDataPair拷贝构造
    DictType(const TestDataPair& other) : id(other.id), names(other.names) {}
    // 支持从TestDataPair移动构造
    DictType(TestDataPair&& other) noexcept : id(std::move(other.id)), names(std::move(other.names)) {}
};

如果需要更通用的适配逻辑,可以使用模板构造函数,兼容所有成员匹配的类型:

struct DictType
{
    DictID id;
    DictName names;

    template <typename T>
    requires requires(T t) {
        { t.id } -> std::convertible_to<DictID>;
        { t.names } -> std::convertible_to<DictName>;
    }
    DictType(T&& other) 
    : id(std::forward<decltype(t.id)>(other.id)), 
      names(std::forward<decltype(t.names)>(other.names)) 
    {}
};

方案3:放宽构造函数的约束条件

将原有的std::convertible_to约束替换为std::constructible_from,允许DictType通过range元素构造,而不要求元素本身可直接转换:

template<std::ranges::input_range R>
requires std::constructible_from<DictType, std::ranges::range_reference_t<R>>
GenericDictionary(R&& definitions)
: userInputList{std::ranges::begin(definitions), std::ranges::end(definitions)}
{
}

这种方式无需修改TestDataPair,因为C++的聚合初始化规则允许从成员匹配的类型构造DictType,std::constructible_from会自动满足该条件。

内容的提问来源于stack exchange,提问作者pacmaninbw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 21:57:02