首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于相同模板的不同类的成员分配。

基于相同模板的不同类的成员分配。
EN

Stack Overflow用户
提问于 2021-12-28 12:01:11
回答 1查看 48关注 0票数 1

假设一个类有两个不同的类,但它们的目的有点“等价”,所以它们有相同的成员,其中一个可以由另一个分配:

代码语言:javascript
复制
struct Pure
{
    QString name;
    int age = 18;
};

struct Observable
{
    QProperty<QString> name;
    QProperty<int> age {18};
    void operator=(const Pure& other)
    {
        name = other.name;
        age = other.age;
    }
};

QProperty是一个Qt中的模板类,但我认为这个问题与Qt无关,因为它适用于任何其他具有T转换/赋值的template <typename T> class Foo

问题是如何避免重复,这样就不能轻易地从一个类中添加或删除一个成员,而忘记在另一个类上这样做,同时仍然保留将一个类的对象分配给另一个类的可能性。

我尝试了几种模板,这似乎是最有希望的:

代码语言:javascript
复制
// Adding two helpers only available in C++ 20 for convenience.
template<typename T>
struct type_identity { using type = T; };    
template<typename T>
using type_identity_t = typename type_identity<T>::type;

template<template<typename T> typename T>
struct State
{
    T<QString> name;
    T<int> age;

//    std::enable_if_t<std::is_same<QProperty<class X>, T>>
//    operator=(const State<type_identity_t>& other)
//    {
//        name = other.name;
//        age = other.age;
//    }
};

int main()
{
    State<type_identity_t> state;
    state.age = 42;
    State<QProperty> observableState;
    observableState = state; // Desired use. Fails to compile without operator=
}

注释掉的代码不编译( error :使用模板参数'T‘需要模板参数),在第一个注释行末尾的T处出现错误,但我不知道如何解决这个问题。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-28 13:55:14

您不能使用std::is_same<QProperty<class X>, T>,因为这是试图将T作为第二个参数传递给is_same,但是它是一个模板,is_same需要一个类型。

您可以创建一个接受模板类的is_same-like特性:

代码语言:javascript
复制
template<template<typename...> class A, template<typename...> class B>
struct is_same_template_class : std::false_type {};

template<template<typename...> class T>
struct is_same_template_class<T, T> : std::true_type {};

// use `is_same_template_class<T, QProperty>`

目前,似乎没有理由限制您的operator=可以做什么。为什么不像这样:

代码语言:javascript
复制
template<template<typename> class T>
struct State
{
    T<QString> name;
    T<int> age;

    template<template<typename> class U>
    State& operator=(const State<U>& other)
    {
        name = other.name;
        age = other.age;
        return *this;
    }
};

我对QT并不熟悉,但是如果您重构一些逻辑,using Observable = QProperty<Pure>;似乎也能工作。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70506780

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档