+ -
当前位置:首页 → 问答吧 → 关于模版例子编译不过,请高手指点

关于模版例子编译不过,请高手指点

时间:2011-12-11

来源:互联网

C/C++ code

class Sun 
{
public:
    template<typename T, int N> operator T[N]& ();
};

void f (int (&)[20]);

void g(Sun s)
{
    f(s);
}



1>e:\设计模式实例\text_02\text_09\text_09.cpp(74) : error C2143: 语法错误 : 缺少“;”(在“&”的前面)
1>e:\设计模式实例\text_02\text_09\text_09.cpp(74) : error C2586: 不正确的用户定义的转换语法 : 非法间接寻址
1>e:\设计模式实例\text_02\text_09\text_09.cpp(74) : error C4430: 缺少类型说明符 - 假定为 int。注意: C++ 不支持默认 int
1>e:\设计模式实例\text_02\text_09\text_09.cpp(74) : error C2238: 意外的标记位于“;”之前
1>e:\设计模式实例\text_02\text_09\text_09.cpp(74) : error C2988: 不可识别的模板声明/定义
1>e:\设计模式实例\text_02\text_09\text_09.cpp(74) : error C2059: 语法错误 : “)”
1>e:\设计模式实例\text_02\text_09\text_09.cpp(75) : error C2143: 语法错误 : 缺少“;”(在“}”的前面)
1>e:\设计模式实例\text_02\text_09\text_09.cpp(75) : error C2238: 意外的标记位于“;”之前
1>e:\设计模式实例\text_02\text_09\text_09.cpp(81) : error C3861: “f”: 找不到标识符

编译器是VC2008,请问是我写错了吗?

作者: H_rui   发布时间: 2011-12-11

肯定是你写错了。

模版也不是那样定义的吧

作者: rrrfff   发布时间: 2011-12-11

converter function和declarator的奇葩语法冲突了。。。
要引用的话自己写个模板类组装类型……不过不会参与隐式转换……
C/C++ code

class Sun
{
public:
    template<typename T>
    operator T&();
};


其实这样就行了。
要是还要有其它转换的话,转换模板不区分参数,实现中调用返回值加些enable_if啥的重载函数实现方便点……


作者: FrankHB1989   发布时间: 2011-12-11

在实际的开发中,这种转换应该不会出现,Sun不是万能的。

真要解决这个语法问题,倒是难不倒C++

C/C++ code

template<typename T> struct traits;

template<typename T, int N>
struct traits<T[N]>
{
    typedef T type;
    enum{number = N};
};

class Sun
{
public:

    template<typename T>
    operator T&()
    {
        typedef typename traits<T>::type type;
        type * p = new type[traits<T>::number];
        return *reinterpret_cast<type(*)[traits<T>::number]>(p);
    }
};

void f(int (&)[20]);

void g(Sun s)
{
    int (&a)[20] = s;
    f(a);
    delete [] &a;
}


作者: Jinhao   发布时间: 2011-12-11

引用 2 楼 frankhb1989 的回复:

converter function和declarator的奇葩语法冲突了。。。
要引用的话自己写个模板类组装类型……不过不会参与隐式转换……
C/C++ code

class Sun
{
public:
template<typename T>
operator T&amp;();
};


其实这样就行了。
要是还要有其它转换的话,转换模板不区分参数,实现中调用返……


+1

C/C++ 把声明分为 specifier 和 declarator 两部分这个设计真是个奇葩……

各种奇形怪状的声明都是让这个东西搞出来的……

作者: hpsmouse   发布时间: 2011-12-11

引用 4 楼 hpsmouse 的回复:

引用 2 楼 frankhb1989 的回复:

converter function和declarator的奇葩语法冲突了。。。
要引用的话自己写个模板类组装类型……不过不会参与隐式转换……
C/C++ code

class Sun
{
public:
template<typename T>
operator T&amp;amp;();
};


其实这样就行了……


declarator真无辜。
int(i); 和 (int)i;

作者: Jinhao   发布时间: 2011-12-11

up up

作者: swust_long   发布时间: 2011-12-11