如何为所有非数组类型专门化模板?
How does one specialize a template for all non-array types?
假设我有一个模板my_type。我希望它具有一般功能,当 T 不是数组时具有一些额外的功能,当 T 是数组时具有其他功能。
假设我有以下模板:
template <typename T>
class my_class<T> {
public:
int f1(); // This function is available for all T
int f2(); // This function is available when T is not an array
int f3(); // This function is available when T is an array
}
因此,如果我尝试:
my_class<int> c1; my_class<int[3]> c2;
c1.f1(); c2.f1(); // both fine
c1.f2(); c2.f3(); // both fine
c1.f3(); c2.f2(); // both should give a compile error
我知道std::unique_ptr
内部这样做。那么它是如何做到的呢?
另一种方式,使用enable_if
.另请注意使用基类来捕获所有常见行为。
#include <type_traits>
template<class T>
struct my_base
{
int f1();
};
template<class T, typename Enable = void>
class my_class;
template<class T>
class my_class<T, std::enable_if_t<std::is_array<T>::value>>
: public my_base<T>
{
public:
int f3(); // This function is available when T is an array
};
template <typename T>
class my_class<T, std::enable_if_t<not std::is_array<T>::value>>
: public my_base<T>
{
public:
int f2(); // This function is available when T is not an array
};
int main()
{
auto a = my_class<int[]>();
a.f1();
// a.f2();
a.f3();
auto na = my_class<int>();
na.f1();
na.f2();
// na.f3();
}
我自己也想通了。下面的代码将执行我所要求的确切操作。
template<typename T>
class my_class {
public:
int f1() { return 1; }
int f2() { return 2; }
};
template<typename T>
class my_class<T[]> {
public:
int f1() { return 1; }
int f3() { return 3; }
};
注意公共函数(f1
(的实现必须被复制。现在有没有办法使用单个实现?(请注意,它不像示例代码中那样像return 1;
那么简单,因此我无法将功能分离到非模板函数中(
相关文章:
- 线程 std::调用未知类型,无法专门化函数错误
- 如何为所有非数组类型专门化模板?
- 如何在同一个模板功能上专门化几种类型?
- 如何为底层类型 int 的枚举专门化类
- 扣除指南的尾随回报类型不是专门化
- C++模板方法专门化联合类型
- 专门化模板数据类型的模板
- 无法专门化 std::hash 以unordered_map存储自定义类型
- 使用非类型模板参数进行专门化模板模板参数
- g++和clang++在结构/类专门化中具有非类型参数的不同行为
- C++模板专门化除一种类型外的所有类型
- 基于类型特征专门化强制转换运算符
- 使用decltype尾部返回类型专门化函数模板
- 可以转发声明的类型模板参与模板专门化
- 专门化泛型类型的函数组
- 错误:T没有命名类型-用于使用强类型枚举的专门化
- 模板类在模板类型之间转换,但也专门化
- 是否可以为模板化类型专门化模板
- 如何在任意依赖类型上专门化模板
- 如何根据模板参数是否具有别名来专门化类型