繁体   English   中英

根据枚举成员的值来专门化模板

[英]Specialize template according to the value of an enum member

我想根据要操作的类的枚举成员来专门化模板函数成员的行为。 我很确定这是可行的,但我看不出来。 这是无法编译的失败尝试(为什么?)。 实际上,我已经为我的项目找到了一个可行的解决方案(使用继承),但这不是很好,我很好奇可以做什么。

#include <iostream>

struct A
{
    enum
    {
        Size = 2    
    };
};

struct B
{
    enum
    {
        Size = 3
    };
};

template <int I>
struct EnumToType
{
    static const int e = I;
};

template <typename T, typename U>
struct C {};

template <typename T>
struct D
{
    typedef C<T, typename EnumToType<T::Size> > Type;
};

template <typename T>
struct C<T, EnumToType<2> >
{
    void operator()()
    {
        std::cout << "hi !" << std::endl;
    }    
};

template <typename T>
struct C<T, EnumToType<3> >
{
    void operator()()
    {
        std::cout << "hello !" << std::endl;
    }    
};

int main()
{
    D<A>::Type da;
    D<B>::Type db;
    da();
    db();
    return 0;
}

一个有用的链接 ...

typedef C<T, typename EnumToType<T::Size> > Type;

这里的typename关键字是没有意义且非法的,只需将其删除即可。

通用模式如下所示(使用bool而不是enum类型,但原理保持不变):

template<typename FalseType, typename TrueType, bool condition> 
struct ConditionalTypeSelector {
    typedef void ResultType;
};

template<typename FalseType, typename TrueType>
struct ConditionalTypeSelector<FalseType,TrueType,false> {
    typedef FalseType ResultType;
};

template<typename FalseType, typename TrueType>
struct ConditionalTypeSelector<FalseType,TrueType,true> {
    typedef TrueType ResultType;
};

在其他地方使用

ConditionalTypeSelector<A,B,(sizeof(A) > sizeof(B))>::ResultType

我不得不质疑您要达到的目标,但这是解决示例的一种方法:

struct A
{
    static const int Size = 2;
};

struct B
{
    static const int Size = 3;
};

template<int message_id>
struct Message;

template<>
struct Message<2>
{
    void operator()()
    {
        std::cout << "hi !" << std::endl;
    }    
};

template<>
struct Message<3>
{
    void operator()()
    {
        std::cout << "hello !" << std::endl;
    }
};

template<typename T>
struct SizeStructToMessage
{
    void operator()()
    {
        Message<T::Size> msg;
        msg();
    }
};

int main()
{
    SizeStructToMessage<A> a;
    SizeStructToMessage<B> b;
    a();
    b();
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM