问题描述
限时送ChatGPT账号..我正在尝试定义一个模板,该模板将指定给定另一种类型 T 的存储类型.我想使用 enable_if 来捕获所有算术类型.下面是我对此的尝试,它抱怨模板用 2 个参数重新声明.我尝试向主模板添加第二个虚拟参数,但出现不同的错误.这怎么办?
I am attempting to define a template that will will specify a storage type given another type T. I'd like to use enable_if to catch all the arithmetic types. Below is my attempt at this which complains the template is redeclared with 2 parameters. I tried adding a 2nd dummy parm to the primary template but get a different error. How can this be done?
#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'
推荐答案
您可以通过向主模板添加第二个参数,然后专门匹配它来实现此目的;你在正确的轨道上,但没有做对.
You can do this by adding a second parameter to the primary template, then specialising to match it; you were on the right track, but didn't do it correctly.
#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.
瞧.
这篇关于将 enable_if 与结构特化一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论