Is it possible to deduce type conversion to template type in C ++?

I want to create a class that is implicitly converted to another class with a template parameter. Here is the MCE that 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 use the example F(b) if both class A and void F are library functions and cannot be changed?

+5
source share
1 answer

It:

 F(b); 

subtract the template argument. As a result, he will not do what you want.

Try explicitly specifying an argument template, for example:

 F<int>(b); 

since you provide the operator () in class B

+4
source

Source: https://habr.com/ru/post/1273606/


All Articles