简体   繁体   中英

C++ template metaprogramming static type checking

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

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).

Use traits technique :

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

The key is SFinae. You have to declare a helper class templated on storage type and provide a definitionodefinitional for one of the two. This way if the specialization exists you know at compile time which storage type you have (the one that you provided a definiton for) and if the substitution fails (which is not an error, SFINAE) you are in the other case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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