Ryednap
Ryednap

Reputation: 312

Defining a function with two different template paramenter

I have the following code

template< typename T>
struct S{
     T x,y;
     S(T a, T b) : x(a) , y(b) {}
};

using Di = S<int>;
using Dd = S<double>;

auto foo(Dd d){
          ..........
}

Now my doubt is: suppose I am calling foo() with parameter of type Di then it's an error of incorrect reference type.

I know that one solution is to use auto here as it works . But in general I want to know is there any other method so that my function works for both parameter types.

Upvotes: 1

Views: 56

Answers (2)

Asteroids With Wings
Asteroids With Wings

Reputation: 17454

S<int> and S<double> (a.k.a. Di and Dd) are two different types.

Period.

It doesn't matter that they are template instantiations.

So, do what you'd normally do when you need a function to take an argument of one of two or more types:

  • make it take a variant, or
  • make it a template, or
  • write an overload

Upvotes: 1

cigien
cigien

Reputation: 60218

You can make the function a template:

template<typename T>
auto foo(S<T> d){
  // ...
}

Now you can call foo with any instantiation of S.


If you want to constrain the function template to only accept instantiations of S with either int or double, you can do that check inside the function:


template<typename T>
auto foo(S<T> d){
  static_assert(std::is_same_v<T, int> || std::is_same_v<T, double>);
  // ...
}

Upvotes: 4

Related Questions