C++ 当无法访问错误时,为什么该程序无法编译?
我正在为可变位大小的像素颜色值创建一个类。不管怎样,我让它工作了,但有点奇怪:C++ 当无法访问错误时,为什么该程序无法编译?,c++,templates,visual-c++,C++,Templates,Visual C++,我正在为可变位大小的像素颜色值创建一个类。不管怎样,我让它工作了,但有点奇怪: #pragma包(推送,1) 模板 结构c{ my_x型; c(){} c(my_type x){this->x=x;} 模板 c convert(){ if(std::is_same::value){ 在您的情况下,当您执行以下操作时,返回*this;//: if (std::is_same<my_type, target_type>::value) { return *this; } if(
#pragma包(推送,1)
模板
结构c{
my_x型;
c(){}
c(my_type x){this->x=x;}
模板
c convert(){
if(std::is_same::value){
在您的情况下,当您执行以下操作时,返回*this;//:
if (std::is_same<my_type, target_type>::value) {
return *this;
}
if(std::is_same::value){
归还*这个;
}
my_type
是uint32_t
而target_type
是uint8_t
。因此,std::is_same::value
是false
,因此返回*这个;
不会执行
但是,它将被编译!并且编译器会报告一个错误,因为在一个假定返回c
的函数中,您肯定不能返回*此
(typec
),因为它们是不同的类型
模板函数的每个路径都必须对编译有效,即使其中一些路径受到运行时执行的保护…在这种情况下,您需要两个版本的函数,一个用于相同类型,另一个用于其他类型。一种可能:
template<typename target_type>
typename std::enable_if<std::is_same<my_type, target_type>::value, c<target_type> >::type
convert() {
return *this;
}
template<typename target_type>
typename std::enable_if<!std::is_same<my_type, target_type>::value, c<target_type> >::type
convert() {
int target_size = sizeof(((c<target_type>*)0)->x);
int my_size = sizeof(x);
if (my_size < target_size) {
return c<target_type>(x << (target_size - my_size) * 8);
}
my_type rounder = ((x >> (my_size - target_size) * 8 - 1) & 9) > 4;
return c<target_type>((x >> (my_size - target_size) * 8) + rounder);
}
模板
typename std::enable_if::type
转换(){
归还*这个;
}
模板
typename std::enable_if::value,c>::type
转换(){
int target_size=sizeof((c*)0)->x;
int my_size=sizeof(x);
如果(我的尺寸<目标尺寸){
返回c(x>(我的尺寸-目标尺寸)*8-1)和9)>4;
返回c((x>>(我的尺寸-目标尺寸)*8)+舍入器);
}
其工作原理是,std::enable_if
在类型相同的情况下启用第一个函数,在所有其他情况下在类型不相同的情况下启用另一个函数。无法从c转换为c
哦,你不能,实际上有什么不清楚的?你的if
中真的有两个背对背的返回吗>声明还是穷人的评论?@πάνταῥεῖ 这种情况永远不会发生。我强烈建议编辑标题以使其更具表现力。@Passenger我试图编辑它以使其更清晰一点……可以进行其他编辑。我已经多次被这种情况所困扰。这是我的解决方案,尽管可能会有更简洁的解决方案。@Rook:我没有提到这一点,因为我不确定这对这个特定的iss有什么帮助你可以复制整个函数,为特殊情况启用一个版本,等等。我想这应该行得通。@Rook:如果你认为有帮助,我可以把这个答案变成“社区wiki”然后你就可以更新它了。看起来其他人已经用这个补丁做了一个答案,所以你还是保持原样吧。
if (std::is_same<my_type, target_type>::value) {
return *this;
}
template<typename target_type>
typename std::enable_if<std::is_same<my_type, target_type>::value, c<target_type> >::type
convert() {
return *this;
}
template<typename target_type>
typename std::enable_if<!std::is_same<my_type, target_type>::value, c<target_type> >::type
convert() {
int target_size = sizeof(((c<target_type>*)0)->x);
int my_size = sizeof(x);
if (my_size < target_size) {
return c<target_type>(x << (target_size - my_size) * 8);
}
my_type rounder = ((x >> (my_size - target_size) * 8 - 1) & 9) > 4;
return c<target_type>((x >> (my_size - target_size) * 8) + rounder);
}