C ++模板元编程静态类型检查 [英] C++ template metaprogramming static type checking

查看:344
本文介绍了C ++模板元编程静态类型检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到我的问题的答案,所以我发布为一个问题。我做了一个小的虚拟示例来解释它:

I couldn't find an answer to my problem so I post it as a question. I make a small dummy example to explain it:

enum STORAGE_TYPE
{
    CONTIGUOUS,
    NON_CONTIGUOUS
};

template <typename T, STORAGE_TYPE type=CONTIGUOUS>
class Data
{
    public:
        void a() { return 1; }
};

// partial type specialization
template <typename T>
class Data<T, NON_CONTIGUOUS>
{
    public:
        void b() { return 0; }
};

// this method should accept any Data including specializations…
template <typename T, STORAGE_TYPE type>
void func(Data<T, type> &d)
{
    /* How could I determine statically the STORAGE_TYPE? */
    #if .. ?? 
        d.a();
    #else
        d.b();
    #endif      
}


int main()
{
    Data<int> d1;
    Data<int, NON_CONTIGUOUS> d2;

    func(d1);
    func(d2);

    return 0;
}

请注意
>我不想要一个专门的func,因为这可以解决它,但我只想有一个通用方法func与内部静态if条件执行代码。
(2),我更喜欢使用标准C ++(而不是C ++ 0x或boost)的解决方案。

Please note that (1) I do not want a specialization of "func", as that could solve it but I just want to have 1 generic method "func" with internal static "if" conditions to execute the code. (2) and I would prefer solution with standard C++ (not C++0x or boost).

推荐答案

使用特征技巧

template <typename T, STORAGE_TYPE type>
struct DataTraits {
  static void callFunction(Data<T, type> &d)
  {
    d.a();
  }
};

template <typename T>
struct DataTraits<T,NON_CONTIGUOUS> {
  static void callFunction(Data<T, NON_CONTIGUOUS> &d)
  {
    d.b();
  }
};


// this method should accept any Data including specializations…
template <typename T, STORAGE_TYPE type>
void func(Data<T, type> &d)
{
    /* How could I determine statically the STORAGE_TYPE? */
    DataTraits<T,type>::callFunction(d);
}

这篇关于C ++模板元编程静态类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆