![](/img/trans.png)
[英]Template Specialization pointer to pointer and array passing template deduction
[英]Template specialization on array pointer with any layer of nesting
我需要編寫一個模板特化,它可以處理數組上的指針(這些東西: char(*)[]
)。 我們將為此編寫此代碼
// our class
template<typename T>
struct CoolStruct
{
static void Print(); // will print "Default"
};
//one specialization for sized arrays
template<typename T, size_t S>
struct CoolStruct<T(*)[S]>
{
static void Print(); // will print "T(*)[sized]"
};
// and one for arrays without size
template<typename T>
struct CoolStruct<T(*)[]>
{
static void Print(); // will print "T(*)[]"
};
當在我們的代碼中時,我們會做這樣的事情:
int (*arrptr)[10];
CoolClass<decltype(arrptr)>::Print();
控制台將按照我們的預期打印“T(*)[size]”(當然,考慮到我們為所有方法編寫了實現)。 但是,如果我們像這樣編寫代碼會怎樣:
int (**arrptr_d)[10];
CoolClass<decltype(arrptr_d)>::Print();
在這種情況下,控制台將實際打印“默認”。 我們可以寫另一個像這樣的專業化:
template<typename T, size_t S>
struct CoolStruct<T(**)[S]>
{
static void Print(); // will print "T(*)[sized]"
};
但我想找到另一個解決方案(當我需要使用int(****)[]
時,我不想再寫十幾個專業)。 那么考慮到我們使用 C++17 標准,有沒有辦法做這樣的事情?
PS 是的,對不起我糟糕的英語; 它不是我的母語。
如果你不關心其他指針,你可以做一個部分特化,將雙指針委托給單指針的特化:
template<typename Pointee>
struct CoolStruct<Pointee**>{
static void Print(){
CoolStruct<Pointee*>::Print();
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.