读书人

请教上这个模板的语法是啥。

发布时间: 2012-09-10 11:02:33 作者: rapoo

请问下这个模板的语法是啥。。

C/C++ code
template<class S, class T>struct SameClass{    template<class Identical, Identical> //A: 这个一般都是 typename A, typename B吧。。这样写有啥特殊语法么?    struct type_match;                         template<class _1>    static char (& func(         type_match< T& (_1::*)(const _1&), &_1::operator => *) )[1]; // 这个必须用这种写法才能有效果,请问下这种写法的含义是啥。。跟之前(A:)的有啥匹配关系?     template<class >    static char (& func(...))[2];     static bool const value = sizeof(func<S>(0)) == 1;}; template<class c1, class c2>bool IsSameClassAs() { return SameClass<c1,c2>::value == 1; }


[解决办法]
1.<class Identical, Identical> 两个参数类型必须一致。这样为后面的func函数的重载埋伏笔

2.template<class _1>
static char (& func(
type_match< T& (_1::*)(const _1&), &_1::operator => *) )[1];

这个是一个函数 func,返回类型是数组的引用 char(&arr)[1] 参数是一个type_match类对象的指针。

T& (_1::*)(const _1&), &_1::operator = 分别是type_match模板类的两个模板参数。




[解决办法]
那么这个呢?
C/C++ code
struct C1{};struct C2{    C1 &operator = (C2 const &);};
[解决办法]
探讨
那么这个呢?

C/C++ code


struct C1
{
};

struct C2
{
C1 &operator = (C2 const &);
};

[解决办法]
这个叫做 Non-type template arguments

呃,这个检测的东西和 SameClass这个名字 不符合

只是检测 S 类中是否有 T& operator=( const S&);

C/C++ code
struct B {};struct A{    B& operator=( const A& );};int main(){    printf( "%d\n" , IsSameClassAs<A,B>() );// 1     printf( "%d\n" , IsSameClassAs<A,A>() );// 0 }
[解决办法]
探讨

引用:
看清楚 &_1::operator =这个函数后面可不是说参数类型不同于_1的

[解决办法]
首先必须保证是class啊,如果你传递 int,long怎么整呢
[解决办法]
type_match和func的关系 就是
func模板函数第一个版本是用 一个type_match<T1,T2>*作为参数的。

至于为什么用 成员函数指针作为type_match的参数无非考虑到 这样一个要求,那就是参数必须是一个class而非其他的类型(int,double等等)。

一旦传递的参数类型(必须是class 类型) 是相互可以替换的那么就会匹配到第一个func,否则就会以匹配失败但不是错误的机制 从而匹配到第2个func模板
[解决办法]
不是这个类型的常量 。而是像我们 int a,b;这样
只是代表两者的类型是一样的。
[解决办法]
探讨

哎,可能是我的表达能力太差了。。
Non-type template arguments应该是这样的:
template<class Identical_1, int Identical_2>
struct type_match;

但是这里的用法是
template<class Identical, int Identical> // 注意这里Identical是一样的!
str……

[解决办法]
其实就是
template
< typename _Type, //在这里声明一个类型参数
_Type _val // 用上面声明的类型定义一个非类型参数
>
class xxxx;

用的时候
xxxx<int,1>
xxxx<char,'c'>
这样都能匹配.
但问题是在一些编译器上,编译不过.

读书人网 >C++

热点推荐