模板不能是拷貝構造函數。 §12.8/ 2,腳註:
Because a template constructor is never a copy constructor, the presence of such a template does not suppress the implicit declaration of a copy constructor. Template constructors participate in overload resolution with other constructors, including copy constructors, and a template constructor may be used to copy an object if it provides a better match than other constructors.
由於模板的說法是const &
,其特徵將是完全一樣的複製情況下,隱式聲明的函數,所以它永遠不會被用作拷貝構造函數。
這可能是好的,因爲在此示例中,您正在使用它作爲轉換構造函數。但是,::
之前的模板參數是未推導的上下文,因此編譯器無法插入A<int>::B
並解析int
。由於專用模板的各種方式,編譯器無法確定哪些A
(如果有)符合要求。您可以在A<float>
之內添加typedef A<int>::B B;
,然後int
和float
將符合U
的條件。
您可以通過使用SFINAE並向類中添加成員類型來解決此問題,以幫助導航層次結構。這裏是一個demo.
#include <typeinfo>
#include <iostream>
template<typename T>
struct A
{
typedef T type;
struct B
{
B() {}
template<typename U>
B(const U& rhs, typename U::nest_A_parent * = NULL) {
std::cout << "copied from type "
<< typeid(typename U::nest_A_parent::type).name() << '\n';
}
private:
typedef A nest_A_parent;
template< typename U >
friend struct B;
};
};
int main()
{
A<int>::B x;
A<double>::B y(x);
}
澄清,什麼是所需的轉換?因爲您不是將int轉換爲double,而是將A :: B轉換爲A :: B,這是另一個類的類。 –
SSight3
@ SSight3:讓我猜猜:Robert試圖用外部refcounts和多態分配來重新實現智能指針... – sehe
轉換是從A :: B到A :: B對於任何T,U。 int和double只是我用過的例子。不,這不是我正在做的事。 –