首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将enable_if与结构专门化结合使用

将enable_if与结构专门化结合使用
EN

Stack Overflow用户
提问于 2017-03-09 01:46:08
回答 1查看 5.6K关注 0票数 6

我正在尝试定义一个模板,它将指定一个给定另一个类型T的存储类型。我想使用enable_if来捕获所有的算术类型。下面是我在这方面的尝试,它抱怨模板被2个参数重新声明。我尝试将第二个虚拟参数添加到主模板,但得到了不同的错误。如何做到这一点?

代码语言:javascript
复制
#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'
EN

回答 1

Stack Overflow用户

发布于 2017-03-09 02:26:24

您可以通过向主模板添加第二个参数来实现这一点,然后指定匹配它;您在正确的轨道上,但没有正确地完成它。

代码语言:javascript
复制
#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.

And voila

票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42678338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档