C++,具有默认参数的模板
C++, templates with default parameters
一个简化的例子:
有一个抽象模板类GCont表示一个通用容器
template <typename Item>
struct TList
{
typedef std::vector <Item> Type;
};
template <typename Item>
class GCont
{
protected:
typename TList <Item>::Type items;
public:
typedef Item type;
virtual ~GCont() = 0 {};
};
和派生的抽象模板类,具有一个隐式参数
template < typename Item, const bool par = true>
class GCont2 : public GCont <Item>
{
public:
GCont2 () : GCont <Item> () {}
virtual ~GCont2() = 0 {};
};
及其对指针的专门化
template <typename Item, const bool par>
class GCont2 <Item *, par> : public GCont <Item *>
{
public:
GCont2 () : GCont <Item *> () {}
virtual ~Cont() {}
};
派生的模板类 Cont
template <typename Point, const bool par = true>
class Cont : public GCont2 <Point, par>
{
public:
Cont() : GCont2 <Point, par>() {}
virtual ~Cont() {}
};
和指针的专用化
template <typename Point, const bool par>
class Cont <Point *, par> : public GCont2 <Point *, par>
{
public:
Cont() : GCont2 <Point *, par> () {}
};
类点:
template <typename T>
class Point
{
protected:
T x, y, z;
};
是否可以编写一个具有通用形式参数的函数 test() 来分配同时使用两者
Cont <Point <T> *> *points
和
Cont <Point <T> *, false> *points
在我的程序中
template <typename T>
void test (Cont <Point <T> *> *points)
{
std::cout << "test";
}
template <typename T>
void test2 (Cont <Point <T> *, false> *points)
{
std::cout << "test2";
}
int _tmain(int argc, _TCHAR* argv[])
{
Point <double> * p = new Point <double>();
Cont <Point <double> *, false> points;
test(&points); //Error
test2(&points); //OK
return 0;
}
在转换过程中,出现以下错误:
Error 1 error C2784: 'void test(Cont<Point<T>*> *)' : could not deduce template argument for 'Cont<Point<T>*> *' from 'Cont<Point,par> *' g:templates_example.cpp 27
感谢您的帮助...
更新状态:
我修剪了代码...但问题仍然存在...我的代码在使用 MSVS 2010 时无法编译相同的错误。
我找到了容器的部分解决方案模板化。
template <typename Container>
void test (Container *points)
{
std::cout << "test";
}
你的代码对我来说完全没问题,你没有给我们你真正拥有的代码。除此之外,您的问题似乎是您想提供错误的输入。您的test
函数需要一个指向点的指针容器(Cont< Point<T>* >
),但您提供了一个点的容器(Cont< Point<T> >
):
Cont< Point<int> >* pc;
// ...
test(pc);
这当然会产生您得到的错误。你需要一个
Cont< Point<int>* >* pc;
也就是说,指针的容器。你在问题中正确地这样做了,但你的真实代码似乎并非如此。
相关文章:
- 使函数参数默认为周围范围
- 如何将值传递给其参数(默认参数)
- 当“std::make_index_sequence”和“std::index_sequence”用于模板参数默认类型时
- C ,构造器中允许的参考参数默认值
- 哪些规则控制参数默认赋值?
- 错误:上一个规范后给出的参数默认参数
- 是否可以设计一个包含模板参数默认值的类
- 构造函数中参数C++默认值
- 如何设置依赖于其他参数的参数默认值
- C++模板参数默认函数实现
- QInput对话框参数默认值
- g++4.8.2上列表方法参数默认初始化时出错
- 在函数定义中指定参数默认值会导致错误 C2143:语法错误:'='之前缺少')'
- 函数模板:将第一个模板参数默认为第二个
- 模板模板参数默认可以引用其他模板类型的参数
- 参数默认为先例参数的值
- 如何修改一个类,使它只有一个成员函数,所有参数默认
- 内置类型的模板参数默认值
- 是否可以使用构造函数或对象作为其他类方法的参数默认值?
- 模板参数默认为更高版本