假设一个类有两个不同的类,但它们的目的有点“等价”,所以它们有相同的成员,其中一个可以由另一个分配:
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。
问题是如何避免重复,这样就不能轻易地从一个类中添加或删除一个成员,而忘记在另一个类上这样做,同时仍然保留将一个类的对象分配给另一个类的可能性。
我尝试了几种模板,这似乎是最有希望的:
// 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处出现错误,但我不知道如何解决这个问题。
发布于 2021-12-28 13:55:14
您不能使用std::is_same<QProperty<class X>, T>,因为这是试图将T作为第二个参数传递给is_same,但是它是一个模板,is_same需要一个类型。
您可以创建一个接受模板类的is_same-like特性:
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=可以做什么。为什么不像这样:
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>;似乎也能工作。
https://stackoverflow.com/questions/70506780
复制相似问题