[英]Recursive templates: compilation error under g++
我試圖遞歸地使用模板來定義(在編譯時)雙元組的d元組。 下面的代碼可以很好地編譯Visual Studio 2010,但是g ++失敗並且抱怨它“無法直接調用構造函數'指向<1> :: point'”。
有誰能請說明這里發生了什么?
非常感謝,喬
#include <iostream>
#include <utility>
using namespace std;
template <const int N>
class point
{
private:
pair<double, point<N-1> > coordPointPair;
public:
point()
{
coordPointPair.first = 0;
coordPointPair.second.point<N-1>::point();
}
};
template<>
class point<1>
{
private:
double coord;
public:
point()
{
coord= 0;
}
};
int main()
{
point<5> myPoint;
return 0;
}
你想做什么:
coordPointPair.second.point<N-1>::point();
看起來你想要顯式地調用point
默認構造函數 - 在構造pair
時已經調用了它。 你不能直接調用構造函數(除非你使用placement new,這在這種情況下是沒有意義的)
只需刪除該行。
如果由於某種原因想要通過從臨時point<N-1>
分配它來覆蓋已構造的.second
,則可以使用coordPointPair.second = point<N-1>();
。
如果對於更復雜的情況,想要將參數傳遞給point
構造函數,則可以在初始化器列表中執行此操作:
point(your_type your_arg) :
coordPointPair(
pair<double, point<N-1> >(0.0, point<N-1>(your_arg_here))
)
{
}
最簡單的解決方案是使用初始化列表:
template <const int N>
class point
{
private:
pair<double, point<N-1> > coordPointPair;
public:
point() : coordPointPair( std::make_pair( 0.0, point<N-1>() ) )
{
}
};
你在那里實現的是不符合c ++標准。 如果你仍想在構造函數中初始化,那么這樣做:
coordPointPair.second = point<N-1>();
coordPointPair.second.point<N-1>::point();
這是非法的。 你想這樣做:
coordPointPair.second = point<N-1>();
順便說一句,它不是必需的,因為在該語句執行時, coordPointPair.second
已經用point<N-1>()
初始化。
但是,如果point<>
有任何非默認構造函數,那么您可以這樣做:
coordPointPair.second = point<N-1>(/*arg, ...*/); //pass the arguments
但同樣,如果你在初始化列表中執行此操作會更好!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.