编译偏特化代码时,揭示"模板 参数“C”与声明不兼容"
编译偏特化代码时,提示"模板 参数“C”与声明不兼容"
去掉注释就不能编译通过,提示
1>main1.cpp(23): error C3855: “container”: 模板 参数“C”与声明不兼容
1>main1.cpp(31): error C2133: “test1”: 未知的大小
1>main1.cpp(31): error C2512: “container”: 没有合适的默认构造函数可用
1>main1.cpp(32): error C2662: “container<A,B,C>::func”: 不能将“this”指针从“container”转换为“container<A,B,C> &”
怎么办?代码写错了还是?求助中!(vs2010+win7)
------解决方案--------------------
特化不是这样的,类模板特化的使用与其普通形式是一样的,类模板实例化时根据模板参数来选择最适合的版本。
#include <iostream>
#include <typeinfo.h>
struct t1{};
struct t2{};
struct t3{};
//template <typename A,typename B,typename C> struct container{
// void func(A a1,B a2,C a3){
// std::cout<<"A: "<<typeid(a1).name()<<std::endl;
// std::cout<<"B: "<<typeid(a2).name()<<std::endl;
// std::cout<<"C: "<<typeid(a3).name()<<'\n'<<std::endl;
// }
//};
template <typename A,typename B,int I> struct container{
void func(A a1,B a2,int a3){
std::cout<<"specialization"<<std::endl;
}
};
const int index=9;
int main()
{
t1 x1;t2 x2;t3 x3;
container<t1,t2,index> test1;
test1.func(x1,x2,index);
std::cout<<"Over"<<std::endl;
getchar();
return 0;
}
去掉注释就不能编译通过,提示
1>main1.cpp(23): error C3855: “container”: 模板 参数“C”与声明不兼容
1>main1.cpp(31): error C2133: “test1”: 未知的大小
1>main1.cpp(31): error C2512: “container”: 没有合适的默认构造函数可用
1>main1.cpp(32): error C2662: “container<A,B,C>::func”: 不能将“this”指针从“container”转换为“container<A,B,C> &”
怎么办?代码写错了还是?求助中!(vs2010+win7)
------解决方案--------------------
特化不是这样的,类模板特化的使用与其普通形式是一样的,类模板实例化时根据模板参数来选择最适合的版本。
#include <iostream>
#include <typeinfo.h>
struct t1{};
struct t2{};
struct t3{};
template <class A, class B, class C>
struct container
{
void func(A a, B b, C c)
{
std::cout<<"A: "<<typeid(a).name()<<std::endl;
std::cout<<"B: "<<typeid(b).name()<<std::endl;
std::cout<<"C: "<<typeid(c).name()<<std::endl;
}
};
template <class A>
struct container<A,A,A>
{
void func(A a1, A a2, A a3)
{
std::cout<<"specialization"<<std::endl;
}
};
const int index=9;
int main()
{
t1 x1;
t2 x2;
t3 x3;
container<t1,t1,t1> test1;
test1.func(x1,x1,x1);
container<t1,t2,t3> test2;
test2.func(x1,x2,x3);
return 0;
}