[英]Constructors for templates that do not have default constructors
我有一個模板類,當前有一個不帶參數的構造函數。 問題在於,在某些情況下,模板中使用的類沒有空的構造函數,該構造函數會產生編譯錯誤。
template <typename T>
class A
{
public:
T Thing;
int number;
A():number(5) {}
};
class B
{
public:
int a;
B(int _a):a(_a) {}
}
A<int> a1; // This is fine
A<B> a2; // This is not fine since B has no default constructor
我曾考慮過可能要添加一個第二個構造函數,該構造函數將對T的引用傳遞給T,然后如果T沒有默認構造函數,則使用enable_if刪除無參數構造函數,但是我不確定這是否可行。 還有其他選擇嗎?
請注意,我不想向類B添加默認構造函數,因為我不想讓B的實例處於未知狀態。
向一些人發表講話,進行了更多研究並找到了解決方案。 使默認構造函數以constexpr靜態成員為模板。 這里是:
template <typename T>
class A
{
public:
T Thing;
int number;
static constexpr bool HasDefaultConstructors = std::is_default_constructible<T>;
// This removes the default constructor if T does not have one
template<bool HDC = HasDefaultConstructors, typename std::enable_if<HDC, int>::type = 0>
A():number(5) {}
A(const Thing &t):T(t) {}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.