模板常量类型转换运算符在 Linux (gcc) 下不起作用
考虑以下程序:
#include <iostream>
template<int s>
class Pack
{
public:
Pack(){}
char data[s];
template<typename X> operator X&(){ return *reinterpret_cast<X*>(data); }
template<typename X> operator X const&()const{ return *reinterpret_cast<const X*>(data); }
};
int main()
{
const Pack<8> p;
const double d(p);
std::cout<<d<<std::endl;
}
它在 Windows 下编译良好。 在linux下我得到:
test.cc: In function ‘int main()’:
test.cc:17: error: passing ‘const Pack<8>’ as ‘this’ argument of ‘Pack<s>::operator X&() [with X = double, int s = 8]’ discards qualifiers
为什么?为什么不采用 const 类型转换运算符?我怎样才能解决这个问题并仍然拥有方便的模板化类型转换运算符(在 const 和非 const 版本中)。 谢谢!
Consider the following program:
#include <iostream>
template<int s>
class Pack
{
public:
Pack(){}
char data[s];
template<typename X> operator X&(){ return *reinterpret_cast<X*>(data); }
template<typename X> operator X const&()const{ return *reinterpret_cast<const X*>(data); }
};
int main()
{
const Pack<8> p;
const double d(p);
std::cout<<d<<std::endl;
}
It compiles fine under Windows.
Under linux I get:
test.cc: In function ‘int main()’:
test.cc:17: error: passing ‘const Pack<8>’ as ‘this’ argument of ‘Pack<s>::operator X&() [with X = double, int s = 8]’ discards qualifiers
Why? Why is it not taking the const type conversion operator? How can I fix this and still have the convenient templated type conversion operator (in const and not const version).
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 C++03 标准,该代码格式不正确,因为模板参数推导将无法根据
const 推导出
。X&
或X const&
双C++03 错过了在推导之前从转换函数的返回类型中剥离引用的声明,因此您永远无法在您的情况下获得匹配。对于 C++0x,此问题将得到修复 并包含在最新的工作文件中,因此它可以使用一些包含追溯修复的编译器进行编译。
你的代码实际上有一个不同的问题:GCC确实实现了缺陷报告解析,因此比较
double
(它在演绎!)针对X
和针对X const
。只有X
匹配,因此只有第一个转换函数是带有const Pack<8>
参数的调用中的单个候选函数 - 这就是 GCC 抱怨缺少的原因const 转换函数。如果您尝试以下代码,它会起作用
According to the C++03 Standard, that code is ill-formed because template argument deduction will not be able to deduce
X&
orX const&
againstconst double
.C++03 missed to state that the reference is stripped off from the return type of the conversion function prior to deduction, so you can never get a match in your case. For C++0x, this will be fixed and is included in the latest working paper, so it may compile with some compilers that include the fix retroactively.
Your code actually has a different problem: GCC does implement that defect report resolution, and therefor compares
double
(it strips off cv-qualifiers prior to deduction!) againstX
and againstX const
. OnlyX
matches and so only that first conversion function is the single candidate in a call with aconst Pack<8>
argument - that's why GCC complains about the missingconst
on the conversion function. If you try the following code it would work