Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to limit template function to specific types?

I got a template function template<typename T> foo (const T&); and I want to restrict the T to only 2 datatypes myVec1 and myVec2, which are defined as

using myVec1 = std::vector<int>;
using myVec2 = std::vector<float>;

Of course, my real world example is by far more complex than this one.

I know that concepts are the way to go, for example

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

template typename<T>
   requires std::floating_point<T>

But how do I have to change above code to allow for the two vector datatypes (myVec1, myVec2) instead of floating point types ?

>Solution :

How do I change the above code to allow the two vector datatypes instead of float?

You don’t modify the std::floating_point because it contains other float types besides float.
Therefore, just write your own concept for the scenario:

using myVec1 = std::vector<int>;
using myVec2 = std::vector<float>;

template<typename T>
concept MyVectorType = std::same_as<T, myVec1> || std::same_as<T, myVec2>;

template<MyVectorType T> void foo(const T& vec) 
{
    // ... implementation
}

Or just use requires to constrain the type T to be either int or float.

template<typename T>
   requires std::same_as<T, int> || std::same_as<T, float>
void foo(const std::vector<T>& vec) 
{
    // .... implementation
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading