cuốn sách gpt4 ai đã làm

c++ - 检查模板参数类型是否被另一个函数接受的 static_assert

In lại Tác giả: Walker 123 更新时间:2023-11-28 02:43:21 30 4
mua khóa gpt4 Nike

我有一个函数模板定义如下:

mẫu 
Test &operator<<(const T &data)
{
std::cout << data << std::endl;
trả lại *cái này;
}

如您所见,我向控制台打印了 dữ liệusử dụng std::cout , 类型是 std::ostream .然而,T可能不是 std::ostream::operator<< 处理的类型.

这就是为什么我想添加 static_assert检查是否T是否被插入运算符接受。目前,我必须检查 std::ostream::operator<< 的每种类型接受:

mẫu 
Test &operator<<(const T &data)
{
static_assert(std::is_arithmetic::value ||
std::is_same::value ||
...
std::is_same::value, "data type must be compliant to std::ostream::operator<< accepted types");

std::cout << data << std::endl;
trả lại *cái này;
}

是否有一种类型特征可以自动做到这一点?你会怎么做?

câu trả lời hay nhất

为什么需要 static_assert?如果插入无效,是否可以简单地使函数不可调用?

mẫu 
auto operator<<(const T &data) -> decltype(std::cout << data, std::declval())
{
std::cout << data << std::endl;
...
}

如果您真的想要一个特征,请参阅 is_stream_insertable

关于c++ - 检查模板参数类型是否被另一个函数接受的 static_assert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25203271/

30 4 0
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress