gpt4 book ai didi

c++ - gcc 奇怪的转换警告(从 ‘A::count_type {aka short unsigned int}’ 转换到 ‘int’ 可能会改变它的值)

转载 作者:行者123 更新时间:2023-11-30 03:46:09 25 4
gpt4 key购买 nike

<分区>

我有以下使用模板的 C++11 代码:

struct Base{
using count_type = unsigned short;
};

template<class T>
struct A : public Base{
using count_type = A::count_type;
// not works even if I comment this

count_type add(T x){
count_type sum = 5;
sum += x.value();
//sum += (count_type) x.value(); // not works even if I cast this, e.g.


return sum;
}
};

struct B{
using count_type = A<B>::count_type;

count_type value(){
return 5; // not works even if I do:
//return (count_type) 5;
//return 5U;
}
};

int main(int argc, char *argv[]){
B b;

A<B> a;

a.add(b);
}

当我尝试使用 -Wconversion 进行编译时,我收到了奇怪的错误消息:

$ g++ -std=c++11  -Wconversion x.cc
x.cc: In instantiation of ‘A<T>::count_type A<T>::add(T) [with T = B; A<T>::count_type = short unsigned int]’:
x.cc:29:9: required from here
x.cc:11:7: warning: conversion to ‘A<B>::count_type {aka short unsigned int}’ from ‘int’ may alter its value [-Wconversion]
sum += x.value();
^

为什么会这样?哪里没有int

如果有人编辑我的问题,我将不胜感激。

注意:clang 不会给出这样的警告。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com