【发布时间】:2010-03-02 06:59:05
【问题描述】:
以下代码失败并显示错误消息:
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(在某些平台上仍然很流行)。
#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;
};
【问题讨论】:
-
如果您的编译器在这种情况下需要关键字
template,那么这是编译器中的一个错误。translate函数的返回类型不依赖于任何模板参数。此处不需要关键字template。您的代码在其原始形式中很好。 -
template这里是必需的,因为str是一个模板方法。 -
那么任何人都可以判断这是否是功能错误?
-
从长远来看,升级 GCC 不是更好吗?您还将获得更好的优化代码。
-
gcc-3.4 在某些平台上只能选择的问题:Cygwin、OpenSolaris。