在上一课 26.4 —— 类模板特化中,我们介绍了一个简单的模板化 Storage 类,以及针对 double 类型的特化:
#include <iostream>
template <typename T>
class Storage
{
private:
T m_value {};
public:
Storage(T value)
: m_value { value }
{
}
void print()
{
std::cout << m_value << '\n';
}
};
template<>
void Storage<double>::print() // fully specialized for type double
{
std::cout << std::scientific << m_value << '\n';
}
int main()
{
// Define some storage units
Storage i { 5 };
Storage d { 6.7 }; // 将导致隐式实例化 Storage<double>
// Print out some values
i.print(); // calls Storage<int>::print (instantiated from Storage<T>)
d.print(); // calls Storage<double>::print (来自 Storage<double>::print() 的显式特化)
}
不过,这个类虽然简单,却有一个隐藏缺陷:当 T 是指针类型时,代码可以编译但运行不正确。例如:
int main()
{
double d { 1.2 };
double *ptr { &d };
Storage s { ptr };
s.print();
return 0;
}
在作者的机器上,输出结果为:
0x7ffe164e0f50
发生了什么?由于 ptr 是 double*,s 的类型是 Storage<double*>,也就是说 m_value 的类型是 double*。调用构造函数时,m_value 会复制 ptr 保存的地址;调用成员函数 print() 时,输出的正是这个地址。
那么如何修复这个问题?
一种方法是为 double* 类型添加完全特化:
#include <iostream>
template <typename T>
class Storage
{
private:
T m_value {};
public:
Storage(T value)
: m_value { value }
{
}
void print()
{
std::cout << m_value << '\n';
}
};
template<>
void Storage<double*>::print() // fully specialized for type double*
{
if (m_value)
std::cout << std::scientific << *m_value << '\n';
}
template<>
void Storage<double>::print() // fully specialized for type double (for comparison, not used)
{
std::cout << std::scientific << m_value << '\n';
}
int main()
{
double d { 1.2 };
double *ptr { &d };
Storage s { ptr };
s.print(); // calls Storage<double*>::print()
return 0;
}
现在会输出正确结果:
1.200000e+00
但这只能解决 T 为 double* 的情况。如果 T 是 int*、char* 或其他指针类型呢?
我们当然不想为每种指针类型都创建完全特化。实际上也做不到,因为用户总能传入指向自定义类型的指针。
指针的偏模板特化
你可能会想到,创建一个针对 T* 类型重载的函数模板:
// doesn't work
template<typename T>
void Storage<T*>::print()
{
if (m_value)
std::cout << std::scientific << *m_value << '\n';
}
这种函数看起来像偏特化函数模板,因为它限制了 T 的类型(必须是指针类型),但 T 仍然是类型模板参数。
遗憾的是,这种方法行不通:截至本文写作时(C++23),函数不能进行偏特化。正如课程 26.5 —— 偏模板特化所述,只有类可以进行偏特化。
因此,我们改为对 Storage 类进行偏特化:
#include <iostream>
template <typename T>
class Storage // 这是主模板类(与之前相同)
{
private:
T m_value {};
public:
Storage(T value)
: m_value { value }
{
}
void print()
{
std::cout << m_value << '\n';
}
};
template <typename T> // 仍然有一个类型模板参数
class Storage<T*> // 这是针对 T* 的偏特化
{
private:
T* m_value {};
public:
Storage(T* value)
: m_value { value }
{
}
void print();
};
template <typename T>
void Storage<T*>::print() // 这是偏特化类 Storage<T*> 的非特化函数
{
if (m_value)
std::cout << std::scientific << *m_value << '\n';
}
int main()
{
double d { 1.2 };
double *ptr { &d };
Storage s { ptr }; // instantiates Storage<double*> from partially specialized class
s.print(); // calls Storage<double*>::print()
return 0;
}
我们把 Storage<T*>::print() 定义在类外,只是为了展示写法,并说明它的定义与上面不可行的偏特化函数 Storage<T*>::print() 相同。不过现在 Storage<T*> 是偏特化类,Storage<T*>::print() 不再是偏特化函数,而是普通函数,因此这是允许的。
值得注意的是,类型模板参数定义为 T 而不是 T*。这意味着 T 会被推导为非指针类型,因此需要指向 T 的指针时必须使用 T*。 另外,偏特化 Storage<T*> 必须定义在主模板类 Storage<T> 之后。
所有权与生命周期问题
上面的偏特化类 Storage<T*> 还有一个潜在问题。由于 m_value 是 T*,它指向传入的对象。如果该对象随后被销毁,Storage<T*> 就会变成悬空。
根本问题在于,Storage<T> 使用值语义(会复制初始化器),而 Storage<T*> 使用引用语义(引用初始化器)。这种不一致很容易引发 bug。
我们可以用几种不同的方法处理这类问题(复杂度依次增加):
- 明确说明
Storage<T*>是一个视图类(具有引用语义),调用者必须保证被指向对象的生命周期至少与Storage<T*>一样长。遗憾的是,这个偏特化类必须与主模板类使用相同的名称,因此无法命名为StorageView之类的名称,只能依靠注释或其他容易被忽略的方式来说明。这不是理想的选择。 - 完全禁止使用
Storage<T*>。其实不一定需要让Storage<T*>存在,因为调用者可以在实例化时解引用指针,使用Storage<T>并复制一份值;对于存储类来说,这种语义更合适。
不过,虽然可以删除重载函数,C++(截至 C++23)不允许删除类。 显而易见的方案是偏特化 Storage<T*>,并在模板实例化时通过某种方式(例如 static_assert)让它无法编译,但这个方案有一个主要缺点:std::nullptr_t 不是指针类型,因此 Storage<std::nullptr_t> 不会匹配 Storage<T*>!
更好的方案是完全避免偏特化,而是在主模板中使用 static_assert,确保 T 属于允许使用的类型。 下面是这种方法的示例:
#include <iostream>
#include <type_traits> // for std::is_pointer_v and std::is_null_pointer_v
template <typename T>
class Storage
{
// Make sure T isn't a pointer or a std::nullptr_t
static_assert(!std::is_pointer_v<T> && !std::is_null_pointer_v<T>, "Storage<T*> and Storage<nullptr> disallowed");
private:
T m_value {};
public:
Storage(T value)
: m_value { value }
{
}
void print()
{
std::cout << m_value << '\n';
}
};
int main()
{
double d { 1.2 };
Storage s1 { d }; // 正确
s1.print();
Storage s2 { &d }; // static_assert because T is a pointer
s2.print();
Storage s3 { nullptr }; // static_assert because T is a nullptr
s3.print();
return 0;
}
- 让
Storage<T*>在堆上复制对象。 如果自行管理全部堆内存,就需要重载构造函数、拷贝构造函数、拷贝赋值运算符和析构函数。 更简单的替代方案是直接使用std::unique_ptr(本教程将在课程 22.5 -- std::unique_ptr 中介绍):
#include <iostream>
#include <type_traits> // for std::is_pointer_v and std::is_null_pointer_v
#include <memory>
template <typename T>
class Storage
{
// Make sure T isn't a pointer or a std::nullptr_t
static_assert(!std::is_pointer_v<T> && !std::is_null_pointer_v<T>, "Storage<T*> and Storage<nullptr> disallowed");
private:
T m_value {};
public:
Storage(T value)
: m_value { value }
{
}
void print()
{
std::cout << m_value << '\n';
}
};
template <typename T>
class Storage<T*>
{
private:
std::unique_ptr<T> m_value {}; // use std::unique_ptr to automatically deallocate when Storage is destroyed
public:
Storage(T* value)
: m_value { std::make_unique<T>(value ? *value : 0) } // or throw exception when !value
{
}
void print()
{
if (m_value)
std::cout << *m_value << '\n';
}
};
int main()
{
double d { 1.2 };
Storage s1 { d }; // 正确
s1.print();
Storage s2 { &d }; // 正确, copies d on heap
s2.print();
return 0;
}
使用类模板偏特化为指针和非指针创建不同实现非常有用:类可以分别处理两者,同时对最终用户完全透明。