是否有可能在C++中推断出模板类型的转换?

Den*_*met 5 c++ oop templates

我想创建一个可以使用模板参数隐式转换为另一个类的类.这是我想要实现的MCE:

#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
}
Run Code Online (Sandbox Code Playgroud)

是否有可能使F(b)例如工作如果两个class Avoid F的库函数,不能modifyed?

gsa*_*ras 4

这:

F(b);
Run Code Online (Sandbox Code Playgroud)

需要模板参数推导。结果,它不会做你想做的事。

尝试显式传递参数模板,如下所示:

F<int>(b);
Run Code Online (Sandbox Code Playgroud)

因为您()在 中提供了一个运算符class B