假設一個有兩個不同的類,但它們的目的有些“等效”,因此它們具有相同的成員,并且一個可以由另一個分配:
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 無關,因為它適用于任何其他template <typename T> class Foo具有轉換/分配到/從的T。
問題是如何避免重復,這樣就不能輕易地從一個類中添加或洗掉成員而忘記在另一個類上這樣做,同時仍然保留將一個類的物件分配給另一個類的可能性。
我用模板嘗試了幾件事,這似乎是最有希望的:
// 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=
}
注釋掉的代碼無法編譯(錯誤:使用模板模板引數“T”需要模板引數),錯誤出現在T第一條注釋行的末尾,但我不知道如何解決這個問題。
uj5u.com熱心網友回復:
您不能使用std::is_same<QProperty<class X>, T>,因為它試圖T作為第二個引數傳遞給is_same,但它是一個模板并且is_same需要一個型別。
您可以創建一個使用is_same模板類的-like trait:
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://www.uj5u.com/qiye/397258.html
上一篇:根據模板引數以不同方式多載運算子
