1

I have a class template with a conversion constructor to the template type. And a function that takes two parameters of that class template. I referred to this question/answer to allow the function to make use of the conversion constructor, however the answer states that you can only call the function if at least one of the arguments is explicitly constructed. Is there any other way to allow the function to be called with all the arguments implicitly constructed?

so this is what I have after referring to the mentioned link. This works if at least argument lhs or rhs are explicitly of type X, and I want it to work even if both are of type T.

template<typename T>
class X {
public:
     X(T t) {}
    friend void func(X lhs, X rhs) {}

};
Community
  • 1
  • 1
mkmostafa
  • 3,071
  • 2
  • 18
  • 47
  • "and I want it to work even if both are of type T." ... mmmm... What do you thing it will happen if one of your mates will put a `template func(U,U) { throw std::logic_error("Not permitted"); }` in one of the headers you include in your code? – Adrian Colomitchi Aug 28 '16 at 11:20

1 Answers1

1

If I correctly understand your problem, you may add overload:

template<typename T>
class X {
public:
     X(T t) {}
    friend void func(const X& lhs, const X& rhs) {}
};

template <typename T> X<T> asX(const T& t) { return {t}; }
template <typename T> const X<T>& asX(const X<T>& x) { return x; }

template<typename LHS, typename RHS>
void func(const LHS& lhs, const RHS& rhs) { return func(asX(lhs), asX(rhs)); }

Demo

Jarod42
  • 203,559
  • 14
  • 181
  • 302