【发布时间】:2019-12-27 16:52:07
【问题描述】:
我正在使用模板进行一些练习,但我遇到了这个问题。我有一个类,它表示具有基础类型和指定编译时起始值的计数器。我想支持计数器类型之间以及具有正确类型的整数类型之间的算术运算符。例如,我想在编译时拒绝以uint8_t 作为基础类型的计数器的总和,并以int 类型的变量。到目前为止一切顺利。
我得到的是,即使是应该正确的操作也无法编译。这里主要展示问题的部分。
#include <iostream>
#include <type_traits>
#include <limits>
template <typename Source, typename Dest, std::enable_if_t<std::is_integral<Source>::value && std::is_integral<Dest>::value, int> =0>
struct type_not_narrow{
static constexpr bool value= std::numeric_limits<Source>::max() <= std::numeric_limits<Dest>::max();
};
template<typename T, T N, std::enable_if_t<std::is_integral<T>::value, int> =0>
class basic_counter{
T cnt;
basic_counter(T initializer): cnt(initializer){}
public:
basic_counter(): cnt(N){};
template <typename T1, T1 N1, typename T2, T2 N2>
friend basic_counter<typename std::common_type<T1,T2>::type, N1+N2> operator+(const basic_counter<T1, N1>& lhs,
const basic_counter<T2, N2>& rhs);
template <typename X, typename U, U M, std::enable_if_t<type_not_narrow<X, U>::value, int>>
friend basic_counter<U,M> operator+(const basic_counter<U, M> lhs, const X step);
operator T() const{
return cnt;
}
};
template <typename T1, T1 N1, typename T2, T2 N2>
basic_counter<typename std::common_type<T1,T2>::type, N1+N2> operator+(const basic_counter<T1, N1>& lhs,
const basic_counter<T2, N2>& rhs){
return {lhs.cnt+rhs.cnt};
}
template<typename X, typename T, T N, std::enable_if_t<type_not_narrow<X, T>::value, int> =0>
basic_counter<T,N> operator+(const basic_counter<T, N> lhs, const X step){
basic_counter<T,N> c=lhs;
c.cnt+=step;
return c;
}
int main() {
basic_counter<unsigned long int, 1> c1;
basic_counter<unsigned long int, 2> c2;
basic_counter<unsigned long int, 3> c3=c2+c1;
unsigned long int ul=5;
int i=5;
char ch=5;
basic_counter<unsigned long int, 2> c4=c2+5;
basic_counter<unsigned long int, 2> c5=c2+i;
basic_counter<unsigned long int, 2> c5bis=c2+ch;
basic_counter<unsigned long int, 2> c6=c2+ul;
//should not compile due to narrowing (and it's correct)
//basic_counter<unsigned long int, 2> c7=c2+5.2;
//basic_counter<uint8_t,0> c8;
//c8=c8+i;
basic_counter<uint8_t,0> c9;
//this should compile
c9=c9+1;
//this should not
c9=c9+2000;
return 0;
}
对于最后一行,如果整数操作数可以成功转换为不窄的类型,我希望它能够编译。例如,加 1 应该编译,而加 2000 不应该编译,因为 1 可以用 uint8_t 表示,而 2000 不能。
【问题讨论】:
-
您的目标是哪个 C++ 标准?除非您有认真的
constexpr支持(阅读 C++14 及更高版本),否则最后一个是不可能的 -
你有一个简单的错误:
<而不是<=在缩小特征。此外,basic_counter<uint8_t,0> c9=c9+1;行在任何情况下都会导致未定义的行为。在 C++17 和之前和在 C++20 中,您不能使用uint8_t的不确定值(初始化完成之前的值),在任何情况下,在其自己的初始化程序中访问变量的值都是 UB。 -
好的,感谢@walmut 的更正。关于你在那几行中关于 UB 的说法,你说得对,我在写这个问题时迅速更改了代码以减少空间,而没有正确注意我在做什么。我将再次进入定义和分配。
-
@DanielJour 你能更好地解释一下“严重的
constexpr支持”是什么意思吗? -
标记为
//this should compile, but it doesn't的行在 gcc 7.4 中为我编译。针对@walnut 的评论所做的编辑是否解决了这个问题?
标签: c++ templates operator-overloading