C++ 是否可以在C+中推断类型转换为模板类型+;?

C++ 是否可以在C+中推断类型转换为模板类型+;?,c++,oop,templates,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(

我想创建一个可以隐式转换为另一个带有模板参数的类的类。以下是我想要实现的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
}
#包括
模板
甲级{
T值;
公众:
(T值){this->value=value;}
T getValue()常量{返回值;}
};
B类{
int值;
公众:
B(int值){this->value=value;}
运算符A()常量{返回一个(值);}
};
模板
void F(A){std::cout

需要模板参数推断。因此,它无法满足您的要求

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

F<int>(b);
F(b);

因为您在
类B中提供了
()
运算符,所以不需要。像您这样调用
F
意味着模板参数推导。这反过来意味着不考虑转换。您可以调用
F(B)
但是。根据设计和用例,可能使
B
A
继承?可能使用
private
继承?
F<int>(b);