为枚举类型参数专门化成员模板

编程入门 行业动态 更新时间:2024-10-12 20:26:21
本文介绍了为枚举类型参数专门化成员模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在下面的代码中,Foo<T>::setValue 非常适合我的目的,除非 T 是名为 TYPE 的类枚举 例如Bar::TYPEBaz:TYPE.

In the code below, Foo<T>::setValue works well for my purposes, except in cases where where T is a class enum named TYPE e.g. Bar::TYPE and Baz:TYPE.

因此,我很感激在不命名 BarBaz 的情况下专门化 Foo<T>::setValue 的帮助,因为可能有几十个此类课程.

Therefore, I'd appreciate help specializing Foo<T>::setValue without naming Bar and Baz, because there could be dozens of such classes.

class Bar
{
public:
    enum TYPE{ ONE , TWO };
};

class Baz
{
public:
    enum TYPE{ SIX , TEN };
};

template<typename T>
class Foo
{
public:
    void setValue(){} // Need a different setValue if T is a class enum

private:
    T m_value;
};


int main()
{
    Foo<int> f1;
    Foo<Bar::TYPE> f2;
    Foo<Baz::TYPE> f3; 
    return EXIT_SUCCESS;
}

推荐答案

你可以这样做:

#include <type_traits>

template<typename T>
class Foo
{
public:
    void setValue() {
      setValueImpl<T>();
    }
private:
    template <class X>
    typename std::enable_if<std::is_enum<X>::value, void>::type
    setValueImpl() { std::cout << "Is enum" << std::endl; }

    template <class X>
    typename std::enable_if<!std::is_enum<X>::value, void>::type
    setValueImpl() { std::cout << "Not enum" << std::endl; } 

    T m_value;
};

其中 enable_if 根据 is_enum 类型特征选择要使用的版本.

Where enable_if picks which version to use based on the is_enum type trait.

示例使用了 C++11 enable_ifis_enum,但 boost 也适用于 pre-C++11.

The example used C++11 enable_if and is_enum but boost has similar for pre-C++11 also.

这篇关于为枚举类型参数专门化成员模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

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

发布评论

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

>www.elefans.com

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