成员模板功能。为什么不编译? [英] Member template function. Why doesn't this compile?

查看:87
本文介绍了成员模板功能。为什么不编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在列表中的成员函数中迭代。在这段代码示例中,我在for-line中遇到编译错误:


在它之前,它没有声明,结束没有声明。


为什么?
该函数甚至不在代码中使用!

 模板< class T& bool Settings :: saveSimpleList(QString k,const T& l){
// ...
for(T :: ConstIterator it = l.constBegin(),end = l.constEnd ; it!= end; ++ it)
{
QString itemValue = QVariant(* it).toString();
// ...
}

return true;
}



我看到,我在模板编程中缺少一些东西。


















$ b

  for(typename T :: ConstIterator it = l.constBegin(),end = l.constEnd(); it!= end; ++ it)
{
QString itemValue = QVariant(* it).toString();
// ...
}

T :: ConstIterator ,编译器可以将其解释为 T ConstIterator c $ c>或类型 T 中定义为 ConstIterator >

如果你的意图是第二个,在这里,你需要添加 typename 告诉编译器。


I whant to iterate in a member function over a list. In this code sample I am getting compiler error in for-line:

Expected ; before it, it not declared, end not declared.

Why? The function is even not used in code!

template <class T> bool Settings::saveSimpleList( QString k, const T & l ){
    //...
    for ( T::ConstIterator it = l.constBegin(), end =l.constEnd(); it != end; ++it )
    {
        QString itemValue = QVariant( *it ).toString();
        //...
    }

    return true;
}

I see, I am missing something in template programming. Thank you for your hints!

解决方案

Do this:

for (typename T::ConstIterator it = l.constBegin(), end =l.constEnd(); it != end; ++it )
{
    QString itemValue = QVariant( *it ).toString();
    //...
}

When writing T::ConstIterator, the compiler can either interpret that as "the static member ConstIterator of type T" or as "the type defined as ConstIterator by a typedef in type T".

If your intent is the second, as here, you need to add typename to tell the compiler.

这篇关于成员模板功能。为什么不编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆