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
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
}