Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

oop

templates

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?

like image 830
Denis Sheremet Avatar asked Nov 23 '17 08:11

Denis Sheremet


1 Answers

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.

like image 53
gsamaras Avatar answered Oct 26 '22 04:10

gsamaras