如何將模板建構式添加到類中,以便明確執行從復雜到復雜的復制初始化并且沒有歧義?是否有編譯器和 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>();
}
};
uj5u.com熱心網友回復:
以便從復雜到復雜的復制初始化顯式且沒有歧義地執行?是否有編譯器和 C 版本/標準不可知的解決方案?
const是的,在這個特定的示例中,您可以向 ctors 的引數添加一個低級別。
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;
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/491228.html
下一篇:概念中的嵌套模板結構
