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

时间:2014-05-22 18:34:51

标签: c++ templates enums

我想根据它所运行的类的枚举成员专门化模板函数成员的行为。我很确定这是可行的,但我无法理解。这是一个没有编译的失败尝试(为什么?)。事实上,我已经为我的项目提供了一个可行的解决方案(使用继承),但这并不好,我很好奇可以做些什么。

#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;
}

有用的link ...

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

一般模式如下所示(使用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

答案 2 :(得分:1)

我不得不质疑你想要实现的目标,但这是解决你的榜样的一种方法:

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;
}
相关问题