我想指定转换A<T>::B为A<U>::B.
template<typename T>
struct A
{
struct B
{
B() {}
template<typename U>
B(const typename A<U>::B& rhs) {}
};
};
int main()
{
A<int>::B x;
A<double>::B y = x;
}
Run Code Online (Sandbox Code Playgroud)
我以为这会这样做,但我得到编译器错误:
从'A <int> :: B'转换为非标量类型'A <double> :: B'request"
为什么我的代码不正确,以及实现所需转换的正确方法是什么?
稍微修改了源代码,以证明这是关于类型推导系统的限制:
template<typename T>
struct A
{
struct B
{
B() {}
template<typename U>
B(const typename A<U>::B& rhs) {}
template<typename U>
B& operator=(const typename A<U>::B& rhs) {}
template<typename U>
B& something(const typename A<U>::B& rhs) {}
};
};
int main()
{
A<int>::B x;
A<double>::B y(x); // fails to deduce
A<double>::B y = x; // fails to deduce
A<double>::B y; y = x; // fails to deduce
x.something(y); // fails to deduce
x.something<double>(y);// NO PROBLEM
}
Run Code Online (Sandbox Code Playgroud)
你看,当我们对编译器提供一点帮助时,就不再有问题了。另请注意实际的编译器错误(gcc)表明它很混乱:
test.cpp|24 col 15| note: candidate is:
test.cpp|15 col 44| note: template<class U> A<T>::B& A<T>::B::something(const typename A<U>::B&)
[with U = U, T = int, A<T>::B = A<int>::B, typename A<U>::B = A<T>::B]
Run Code Online (Sandbox Code Playgroud)
注意其中的部分U = U(即未解决的部分)