- 论坛徽章:
- 0
|
下午看了一篇关于boost function 源码剖析的文章(http://dev.yesky.com/196/2012196_1.shtml),上面出现了function 偏特化技术的讲解,自己动手在VC2005做了个测试,发现,按照他预处理后的程序无法编译。
我类似的写了几个模板偏特化,请大家指点。
// 200801.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
template<typename T1, typename T2, typename Allocate>
class T1_base
{
public:
T1_base()
{
cout<<"print T1_base(templeate)"<<endl;
}
};
template<typename T1, typename T2, typename Allocate>
class T2_base
{
public:
T2_base()
{
cout<<"print T1_base(templeate)"<<endl;
}
};
template<typename T1, typename T2, typename Allocate>
class T1_base<T1(T2), Allocate>
:public T2_base<T1, T2, allocate>
{
public:
T1_base()
{
cout<<"print T1_base(T2)"<<endl;
}
};
int add(int)
{
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
T1_base<int(int) ,int, int> base;
return 0;
}
|
上面的偏特化报错如下:
e:\source_work\1.0 work\work\200801\200801\200801.cpp(33) : error C2976: “T1_base”: 模板 参数太少
1> e:\source_work\1.0 work\work\200801\200801\200801.cpp(11) : 参见“T1_base”的声明
1>e:\source_work\1.0 work\work\200801\200801\200801.cpp(40) : error C2953: “T1_base”: 类模板已经定义
1> e:\source_work\1.0 work\work\200801\200801\200801.cpp(11) : 参见“T1_base”的声明
1>e:\source_work\1.0 work\work\200801\200801\200801.cpp(50) : error C2133: “base”: 未知的大小
1>e:\source_work\1.0 work\work\200801\200801\200801.cpp(50) : error C2512: “T1_base”: 没有合适的默认构造函数可用
修改如下,则可以:
template<typename T1, typename T2, typename Allocate>
class T1_base<T1(T2), T2, Allocate>
:public T2_base<T1, T2, allocate>
{
public:
T1_base()
{
cout<<"print T1_base(T2)"<<endl;
}
}; |
既然事实如此,为什么作者在写这篇文章是举例:
template<typename R,typename T0,typename Allocator>
class function<R(T0),Allocator> //对R(T0)函数类型的偏特化版本
:public function1<R,T0,Allocator> //为R(T0)形式的函数准备的基类,在下面讨论
{
typedef function1<R,T0,Allocator> base_type;
typedef function selftype;
struct clear_type{}; //马上你会看到这个蹊跷的类型定义的作用
public:
function() : base_type() {} //默认构造
template<typename Functor> //模板化的构造函数,为了能够接受形式兼容的仿函数对象
function(Functor f, typename enable_if<
(ice_not<(is_same<Functor, int>::value)>::value),
int
>::type = 0) :base_type(f){}
function(clear_type*) : base_type() {} //这个构造函数的作用在下面解释
self_type& operator=(const self_type& f) //同类型function对象之间应该能够赋值
{
self_type(f).swap(*this); //swap技巧,细节见《Effective STL》
return *this;
}
...
};
|
应该是错误的。
请大家指点啊。谢谢。
[ 本帖最后由 guhan010 于 2009-6-25 23:06 编辑 ] |
|