歧义类模板转换



如何将模板构造函数添加到类中,以便显式地执行从复杂到复杂的复制初始化,而不会产生歧义?是否有一个解决方案是编译器和c++版本/标准不可知的?是否有一种方法只需要定义构造函数而不需要额外的操作符重载?

我包含了模板复制构造函数和操作符重载(类中定义的最后两个方法),但编译器给了我以下消息:

Compilation error
main.cpp: In function ‘void testTemplateConstructor()’:
main.cpp:74:27: error: conversion from ‘complex<float>’ to ‘complex<double>’ is ambiguous
complex<double> cd = cf;
^~
main.cpp:35:5: note: candidate: complex<T>::operator complex<X>() [with X = double; T = float]
operator complex<X>(){
^~~~~~~~
main.cpp:29:5: note: candidate: complex<T>::complex(complex<X>&) [with X = float; T = double]
complex(complex<X>& arg) {
^~~~~~~

这是正在使用的测试用例。

void testTemplateConstructor() {
complex<float> cf{1.0f, 2.0f};
complex<double> cd = cf;

Assert(cf.real()==cd.real(), "Real parts are different.");
Assert(cf.imag()==cd.imag(), "Imaginary parts are different.");
}
template <typename T> class complex{    

private:
typedef complex<T> complexi;
T real_;
T imag_;

public:
complex(){
real_ = 0;
imag_ = 0;
}
complex(T a, T b){
real_ = a;
imag_ = b;
}
complex(T a){
real_ = a;
}
complex(complex<T>& comp){
real_ = comp.real_;
imag_ = comp.imag_;
}
template <typename X>
complex(complex<X>& arg) { 
real_ = arg.real_;
imag_ = arg.imag_;
}

template <typename X>                  
operator complex<X>(){
return complex<T>();
}
};

使复制初始化从复杂到复杂是明确无误的吗?是否有一个解决方案是编译器和c++版本/标准不可知的?

是的,在这个特殊的例子中,您可以将低级别的const添加到参数中。

template <typename T> class complex{    

public:
typedef complex<T> complexi;
T real_;
T imag_;

public:
complex(){
real_ = 0;
imag_ = 0;
}
complex(T a, T b){
real_ = a;
imag_ = b;
}
complex(T a){
real_ = a;
}
complex(const complex<T>& comp){
std::cout<<"nornal version";;
real_ = comp.real_;
imag_ = comp.imag_;
}
template <typename X>
complex(const complex<X>& arg) { 
std::cout<<"template version";;
real_ = arg.real_;
imag_ = arg.imag_;
}


};
void testTemplateConstructor() {
complex<float> cf{1.0f, 2.0f};
complex<double> cd = cf;


}

演示

这是我正在寻找的解决方案,这适用于c++ 11标准和编译器版本,如x86_64 gcc 4.7.1和clang 3.4.1。除了使用static_cast之外,唯一的区别是使用getter。

using namespace std;
template <typename T> class complex{    

public:
typedef complex<T> complexi;
T real_;
T imag_;

public:
complex(){
real_ = 0;
imag_ = 0;
}
complex(T a, T b){
real_ = a;
imag_ = b;
}
complex(T a){
real_ = a;
}
complex(const complex<T>& comp){
real_ = comp.real_;
imag_ = comp.imag_;
}
template <typename X>
complex(const complex<X>& rhs){
real_ = static_cast<T>(rhs.real());
imag_ = static_cast<T>(rhs.imag());
}
T real() const {
return real_;
}
T imag() const {
return imag_;
}

};

相关内容

  • 没有找到相关文章

最新更新