我想实现一个从文件中加载 1D/2D/3D 点的功能...模板参数 Point 可以是 1D 2D 3D 点。
template <typename Point>
void List <Point> ::load ( const char *file)
{
...
for ( unsigned int i = 0; i < file.size(); i++ )
{
if ( file[i].size() == 1 )
{
items.push_back( Point ( atof ( file[i][0].c_str() ) ) );
}
else if ( file[i].size() == 2 )
{
items.push_back( Point ( atof ( file[i][0].c_str() ), atof ( file[i][1].c_str() ) ) );
}
else if ( file[i].size() == 3 )
{
items.push_back(Point ( atof ( file[i][0].c_str() ), atof ( file[i][1].c_str() ), atof ( file[i][2].c_str() ) ) );
}
}
}
如果我为 2D 点运行此函数,则 2D 点没有具有三个参数的构造函数。3D点也会出现同样的情况......
List <Point2D> list1;
list1.load("file"); //Error
List <Point3D> list2;
list2.load("file"); //Error
Error 275 error C2661 : no overloaded function takes 3 arguments
Error 275 error C2661 : no overloaded function takes 2 arguments
如何高效地设计这样的功能?语法有些简化,它只是一个说明性示例。