将enable_if与结构专业化
Using enable_if with struct specialization
我正在尝试定义一个模板,该模板将指定给定其他类型T的存储类型。我想使用enable_if来捕获所有算术类型。以下是我对此指出模板的尝试,该模板已用2个参数重新编写。我尝试在主模板中添加第二个虚拟模拟,但会遇到不同的错误。如何完成?
#include <string>
#include <type_traits>
template <typename T> struct storage_type; // want compile error if no match
// template <typename T, typename T2=void> struct storage_type; // no joy
template <> struct storage_type<const char *> { typedef std::string type; };
template <> struct storage_type<std::string> { typedef std::string type; };
template <typename T, typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
struct storage_type { typedef double type; };
// Use the storage_type template to allocate storage
template<typename T>
class MyStorage {
public:
typename storage_type<T>::type storage;
};
MyStorage<std::string> s; // uses std::string
MyStorage<const char *> s2; // uses std::string
MyStorage<float> f; // uses 'double'
您可以通过将第二个参数添加到主模板中,然后专门匹配它来做到这一点;您在正确的轨道上,但没有正确做。
#include <string>
#include <type_traits>
// template <typename T> struct storage_type; // Don't use this one.
template <typename T, typename T2=void> struct storage_type; // Use this one instead.
template <> struct storage_type<const char *> { typedef std::string type; };
template <> struct storage_type<std::string> { typedef std::string type; };
// This is a partial specialisation, not a separate template.
template <typename T>
struct storage_type<T, typename std::enable_if<std::is_arithmetic<T>::value>::type> {
typedef double type;
};
// Use the storage_type template to allocate storage
template<typename T>
class MyStorage {
public:
typename storage_type<T>::type storage;
};
MyStorage<std::string> s; // uses std::string
MyStorage<const char *> s2; // uses std::string
MyStorage<float> f; // uses 'double'
// -----
struct S {};
//MyStorage<S> breaker; // Error if uncommented.
和voila。
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 如何使用默认参数等选择模板专业化
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 如何在 C# 中映射双 C 结构指针?
- 模板化建造师专业化
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 多成员Constexpr结构初始化
- C++将文本文件中的数据读取到结构数组中
- 在模板专业化期间,如何设置C 结构中的静态字段
- 可以在模板专业化中互换使用类和结构
- 将enable_if与结构专业化
- 如何为所有“ std :: array”的工厂结构进行部分专业化,该结构超过4`元素
- 模板结构专业化使用TypName ::
- 模板中依赖于模板类型的结构的专业化