Compile time type checking C++

后端 未结 3 916
春和景丽
春和景丽 2021-01-14 00:22

I have created a type list. I then create a class using a template passing the type list. When I call the print function of the class with a some types not specified they ar

3条回答
  •  孤独总比滥情好
    2021-01-14 01:03

    You would have to make your print function into a template and then check whether the types match:

    template 
    void print(const U & u)
    {
      // use std::is_same::type, typename std::decay::type>::value
    }
    

    Here I'm stealing is_same and decay from , but if you don't have C++11, you can either take them from TR1 or from Boost, or just write them yourself, as they're very simple type modifier classes.

    The conditional would best go into a static_assert, which is another C++11 feature, but there exist similar constructions for C++98/03 that produce a compile-time error under a certain condition.

提交回复
热议问题