Compile time type checking C++

后端 未结 3 877
春和景丽
春和景丽 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 <typename U>
    void print(const U & u)
    {
      // use std::is_same<typename std::decay<T::Head>::type, typename std::decay<U>::type>::value
    }
    

    Here I'm stealing is_same and decay from <type_traits>, 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.

    0 讨论(0)
  • 2021-01-14 01:07

    Add a private function template

    template<typename T> void print(T);
    

    which doesn't need an implementation. This should catch all types for which no explicit print exists, and since it is private, it will give an error message.

    0 讨论(0)
  • 2021-01-14 01:09

    You could take your arguments by non-const reference, forcing them to be the exact same type. However you can no longer use it with const variables or literals.

    0 讨论(0)
提交回复
热议问题