将 enable

编程入门 行业动态 更新时间:2024-10-14 16:24:50
本文介绍了将 enable_if 与结构特化一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-05-01 06:10:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1405314.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:enable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!