I want to create a class which is implicitly convertable to another class with template parameter. Here is MCE of what I want to achieve:
#include <iostream>
template <typename T>
class A {
T value;
public:
A(T value) {this->value = value;}
T getValue() const {return value;}
};
class B {
int value;
public:
B(int value) {this->value = value;}
operator A<int>() const {return A(value);}
};
template <typename T>
void F(A<T> a) {std::cout << a.getValue() << std::endl;}
void G(A<int> a) {std::cout << a.getValue() << std::endl;}
int main()
{
B b(42);
F(b); // Incorrect
F((A<int>)b); // Correct
G(b); // Also correct
}
Is it possible to make F(b)
example work if both class A
and void F
are library functions and can't be modifyed?
This:
F(b);
requires template argument deduction. As a result, it won't do what you want.
Try passing explicitly the argument template, like this:
F<int>(b);
since you provide a ()
operator in class B
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With