将enable_if与struct specialization一起使用

Gle*_*enn 3 c++ templates enable-if

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

#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'
Run Code Online (Sandbox Code Playgroud)

Jus*_*ica 10

您可以通过向主模板添加第二个参数,然后专门匹配它来完成此操作; 你是在正确的轨道上,但没有正确地做到这一点.

#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.
Run Code Online (Sandbox Code Playgroud)

.