gpt4 book ai didi

c++ - 函数和内部函数相同的参数

转载 作者:行者123 更新时间:2023-11-30 03:19:06 24 4
gpt4 key购买 nike

有人可以帮助我如何实现我的函数只接受可以在其中调用该函数的参数类型吗?

我有一个 Logger 类,它可以从 Arduino 代码的 setup() 函数中的 HardwareSerial 对象开始。
然后在 loop() 中,我想调用 Logger.print() 函数,该函数应该只接受那些参数 what HardwareSerial.print() 可以调用。

这是我丑陋且无效的尝试:

template <typename... ARGS>
size_t print(const ARGS &... args) {
if (serial != NULL) {
if (sizeof...(args) == 2) {
return this->serial->print(args[0], args[1]);
} else if (sizeof...(args) == 1) {
return this->serial->print(args[0]);
}
}
return 0;
}

template <typename T>
size_t print(const T &t, typename std::enable_if<std::is_convertible<const __FlashStringHelper *, T>::value ||
std::is_base_of<const String &, T>::value ||
std::is_array<T>::value ||
//std::is_same<char[std::extent<T>::value], T>::value ||
std::is_same<char, T>::value ||
std::is_same<char *, T>::value ||
std::is_same<const char *, T>::value ||
std::is_same<unsigned char, T>::value ||
std::is_same<int, T>::value ||
std::is_same<unsigned int, T>::value ||
std::is_same<long, T>::value ||
std::is_same<unsigned long, T>::value ||
std::is_same<double, T>::value ||
std::is_convertible<const Printable &, T>::value ||
std::is_convertible<struct tm *, T>::value,
T>::type * = 0) {
if (serial != NULL) {
return this->serial->print(t);
}
retrun 0;
}

最佳答案

当您使用 decltype 进行 SFINAE 检查时,检测函数是否可以被调用是小菜一碟:

template <typename... ARGS>
auto print(const ARGS &... args) -> decltype(this->serial->print(args...)) {
if (serial != NULL) {
return this->serial->print(args...);
}
return 0;
}

关于c++ - 函数和内部函数相同的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54092429/

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