c++ - 如何解决 gcc-3.4 错误(或者这可能不是错误)?

标签 c++ gcc

以下代码失败并显示错误消息:

t.cpp: In function `void test()':
t.cpp:35: error: expected primary-expression before '>' token
t.cpp:35: error: expected primary-expression before ')' token

现在我没有发现代码有任何问题,它可以使用 gcc-4.x 和 MSVC 2005 进行编译,但不能使用 gcc-3.4(gcc-3.4 在某些平台上仍然很流行)进行编译。

#include <string>
#include <iostream>

struct message {
        message(std::string s) : s_(s) {}
        template<typename CharType>
        std::basic_string<CharType> str()
        {
                return std::basic_string<CharType>(s_.begin(),s_.end());
        }
private:
        std::string s_;
};


inline message translate(std::string const &s)
{
        return message(s);
}


template<typename TheChar>
void test()
{
        std::string s="text";
        std::basic_string<TheChar> t1,t2,t3,t4,t5;

        t1=translate(s).str<TheChar>(); // ok

        char const *tmp=s.c_str();
        t2=translate(tmp).str<TheChar>(); // ok

        t3=message(s.c_str()).str<TheChar>(); // ok

        t4=translate(s.c_str()).str<TheChar>(); // fails

        t5=translate(s.c_str()).template str<TheChar>(); // ok

        std::cout << t1 <<" " << t2 <<" " << t3 << " " << t4 << std::endl;
}

int main()
{
        test<char>();
}

是否可以在 translate 函数和 message 类的级别上解决这个问题,或者我的代码可能是错误的,如果是的话,在哪里?

编辑:

Bugs related to template-functions in GCC 3.4.6说我需要使用关键字 template 但我应该吗?

这是一个错误吗?我必须编写 template 关键字吗?因为在所有其他情况下我都不需要?而且它非常连线,当我使用“.c_str()”成员函数时,我不必编写它。

为什么 gcc-4 并不总是一个选择

在 Cygwin 下使用 gcc-4 编译时该程序无法启动

#include <iostream>
#include <locale>

class bar : public std::locale::facet  {
public:
        bar(size_t refs=0) : std::locale::facet(refs)
        {
        }
        static std::locale::id id;
};

std::locale::id bar::id;


using namespace std;

int main()
{
        std::locale l=std::locale(std::locale(),new bar());
        std::cout << has_facet<bar>(l) << std::endl;
        return 0;
}

并且此代码无法在 OpenSolaris 2009 下使用 gcc-4.3 进行编译 - 破坏概念检查...

#include <map>
struct tree {
   std::map<int,tree> left,right;
};

最佳答案

正如其他地方提到的,这似乎是一个编译器错误。很公平;这些都存在。您可以采取以下措施:

#if defined(__GNUC__) && __GNUC__ < 4
// Use erroneous syntax hack to work around a compiler bug.
t4=translate(s.c_str()).template str<TheChar>();
#else
t4=translate(s.c_str()).str<TheChar>();
#endif

GCC 始终将 __GNUC__ 定义为主要编译器版本号。如果需要,您还可以获得 x.y.z 版本号的 y 和 z 的 __GNUC_MINOR____GNUC_PATCHLEVEL__

关于c++ - 如何解决 gcc-3.4 错误(或者这可能不是错误)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2361388/

相关文章:

c++ - 构造函数中使用lambda的C++类

c - GCC 正在生成充满零的二进制文件

c++ - GCC 无法向量化这个简单的循环 ('number of iterations cannot be computed' ) 却在同一代码中管理了一个类似的循环?

linux - 请求 makefile 编写技巧

c++ - 查找轮廓 OpenCV C++

c++ - 将 vector<vector<Point>> X 转换为 IplImage* 或 cv::Mat*

c - 为 __uint128 数字预处理 C 十六进制字符串

gcc - 无法配置 gcc - 找不到 mpfr

c++ - 如何在 Windows 上以编程方式等效地查询 proc 文件系统?

c++ - 为什么 Windows Visual Studio 会损坏 C 样式字符串而 Linux 不会?