我想設計一個帶有兩個引數的模板類,這些引數在編譯時基于兩個互斥基類之一的模板引數繼承。我想對我來說保持簡單,所以想出了這個作業示例。我std::conditional
根據模板引數得到的繼承條件。我設定的條件繼承的專用方法std::enable_if
。
class Empty {};
template<typename T>
class NonEmpty { protected: std::vector<T> mObjects; };
template< typename A, typename B = A>
class Storage : public std::conditional<std::is_same<A, B>::value, Empty, NonEmpty<B>>::type
{
public:
template<typename C = B, typename std::enable_if<std::is_same<C, A>::value>::type* = nullptr>
void doStuff()
{
// one argument or two arguments with same type
// do stuff ...
};
template<typename C = B, typename std::enable_if<std::is_same<C, A>::value>::type* = nullptr>
void doSomthingElse()
{
// one argument or two arguments with same type
// do something exclusively just for this argument constellation ...
};
template<typename C = B, typename std::enable_if<!std::is_same<C, A>::value>::type* = nullptr>
void doStuff()
{
// two arguments with different types
// do stuff with inherited variables of NonEmpty-Class ...
};
};
int main()
{
EmptyClass<int> emp;
NonEmptyClass<int, float> nonemp;
emp.doStuff();
emp.doSomethingElse();
nonemp.doStuff();
}
有沒有更好的方法來解決它,或者我現有的解決方案有什么改進?(我在 C 14 中使用 GCC 8.1.0)
uj5u.com熱心網友回復:
在我看來,你最好部分專門化模板,因為兩個版本的整個實作是完全獨立的。這樣你也可以不繼承任何類而不是繼承一個空類。
template<typename T>
class NonEmpty {
protected:
std::vector<T> mObjects;
};
template<typename A, typename B = A>
class Storage : public NonEmpty<B>
{
public:
void doStuff()
{
std::cout << "doStuff() different types\n";
};
};
template<typename A>
class Storage<A, A>
{
public:
void doStuff()
{
std::cout << "doStuff() same types\n";
};
void doSomethingElse()
{
std::cout << "doSomethingElse()\n";
};
};
int main() {
Storage<int> emp;
Storage<int, float> nonemp;
emp.doStuff();
emp.doSomethingElse();
nonemp.doStuff();
}
uj5u.com熱心網友回復:
我沒有看到將它們全部放在一個模板中的好處。我的印象是,您通過將所有內容都填充到一個模板中而使事情變得復雜,但隨后需要為每個單獨的方法選擇哪個版本。兩個單獨的類:
template <typename A, typename B>
struct inherits_from_empty : Empty {
// implement methods here, no sfinae needed
};
和
template <typename A, typename B>
struct inherits_from_nonEmpty : NonEmpty<A> {
// implement methods here, no sfinae needed
};
可以通過以下方式選擇
template <typename A,typename B>
using Storage = std::conditional_t< put_condition_here<A,B> , inherits_from_empty<A>,inherits_from_nonEmpty<A>>;
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/491520.html