mardi 20 novembre 2018

C++ define functions based on template types

Let's say I have the following struct MyPairType.

template<typename F, typename S>
struct MyPairType {
  F first;                                                                           
  S second;                                                                        
  VPairType() { }
  VPairType(F f, S s) { first = f; second = s; }
  operator F() const { return first; }
  operator S() const { return second; }
};

When I try to use MyPairType<A, B> (for any types A and B s.t. A != B), it works fine. However, when I try to use MyPairType<T, T> (for any type T), it fails because the two conversion operators are same:

error: ‘MyPairType<F, S>::operator S() const [with F = int; S = int]’ cannot be overloaded
   operator S() const { return second; } 
   ^
error: with ‘MyPairType<F, S>::operator F() const [with F = int; S = int]’
   operator F() const { return first; }

I found that this can be fixed using a combination of std::enable_if and std::is_same, but it would require templating the operator function which is not desirable.

How can I fix this issue?

Aucun commentaire:

Enregistrer un commentaire