我试图研究C++编译器在可变模板构造函数和转换运算符同时存在时如何解决隐式转换。以下是一个最小化的示例:
当我写下:
#include <iostream>
class A {
public:
A () {}
template<typename...tTypes> A (tTypes...pArgs) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
class B {
public:
operator A () const {
std::cout << __PRETTY_FUNCTION__ << std::endl;
return A();
}
};
int main() {
B b;
A a = b;
}
运行时,我得到了这个输出:
B::operator A() const
。所以它使用了转换运算符(正如我所预期的)。实时示例在http://ideone.com/ZZ2uBz。但当
A
是一个模板时,结果会有所不同:#include <iostream>
template<typename tType>
class A {
public:
A () {}
template<typename...tTypes> A (tTypes...pArgs) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
class B {
public:
template<typename tType>
operator A<tType> () const {
std::cout << __PRETTY_FUNCTION__ << std::endl;
return A<tType>();
}
};
int main() {
B b;
A<float> a = b;
}
运行此程序时,我得到了这个输出:
A<tType>::A(tTypes ...) [with tTypes = {B}; tType = float]
。因此,它使用了A
的可变参数构造函数,而不是B
中的转换运算符。在http://ideone.com/u9Rxuh上有实时示例。有人能解释一下为什么会有这种差异吗?转换运算符难道不应该比构造函数优先吗?
我知道我可以显式调用转换运算符(
A<float> a = b.operator A<float>();
),但那不是我想要的。