Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wish to define a template such as below w/ the requirement y > x
C++
template<int x, int y>
struct cfoobar {};

May I please seek your kind assistance in learning how to compose such a requirement. Thank You Kindly - Cheerio

What I have tried:

template<int x, int y> requires y > x
struct cfoobar {};
Posted
Updated 9-Jun-21 20:02pm

1 solution

Your syntax is correct. Try, for instance
C++
#include <iostream>
#include <array>
#include <cstddef>

template<int x, int y> requires y > x
struct cfoobar
{
  std::array<double, x> xa;
  std::array<double, y> ya;
};


int main()
{
  cfoobar<7,5> cf1;
  cfoobar<5,7> cf2;
}



GCC 9 output:
g++ -fconcepts -Wall foo.cpp
foo.cpp: In function ‘int main()’:
foo.cpp:16:13: error: template constraint failure
   16 |  cfoobar<7,5> cf1;
      |             ^
foo.cpp:16:13: note:   constraints not satisfied
foo.cpp:16:13: note: ‘y > x’ evaluated to false
foo.cpp:16:15: warning: unused variable ‘cf1’ [-Wunused-variable]
   16 |  cfoobar<7,5> cf1;
      |               ^~~
foo.cpp:17:15: warning: unused variable ‘cf2’ [-Wunused-variable]
   17 |  cfoobar<5,7> cf2;
 
Share this answer
 
Comments
Greg Utas 10-Jun-21 5:39am    
5. I learned some C++20!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900