Search code examples
c++templatesc++20type-traits

check if type has certain value types and the keyword value_type itself using c++20


I have following code

#include <type_traits>

template<typename T, typename U, typename Tout>
requires std::is_integral< typename T::value_type >
&& std::is_floating_point< typename U::value_type >
&& std::is_floating_point< typename Tout::value_type >
class test
{
    test() =default;
};


int main(int argc, char const *argv[])
{
    /* code */
    return 0;
}

I essentially want to ensure that the template argument have certain types, integral or floating point. There are two issues:

  1. The code does not compile. Complains that it needs '(' for function style cast or type construction. Not sure why?
  2. I am assuming that T,U,Tout all have the keyword value_type. I also want the class to work out if somebody is passing a raw pointer to an integral type or floating point. Is there an easy way to incorporate that?
  3. If not, how can we ensure that the error message is very clear when somebody tries to pass a template argument which does not have the value_type

Solution

    1. You have several some typos in the code you posted. Cleaned up, the following does what you're looking for:
    template<typename T, typename U, typename Tout>
    requires std::is_integral_v<typename T::value_type>
          && std::is_floating_point_v<typename U::value_type>
          && std::is_floating_point_v<typename Tout::value_type>
    class test {
    public:
        test()=default;
    };
    
    1. That's a big ask. Maybe someone else can fill in that blank.
    2. The error message generated by the compiler (g++ 10.2 here) seems clear enough:
    int main() {
      test<int, int, int> t;
    }
    
    main.cpp: In function 'int main()':
    main.cpp:16:21: error: template constraint failure for 'template<class T, class U, class Tout>  requires (is_integral_v<typename T::value_type>) && (is_floating_point_v<typename U::value_type>) && (is_floating_point_v<typename Tout::value_type>) class test'
       16 |   test<int, int, int> t;
          |                     ^
    main.cpp:16:21: note: constraints not satisfied