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

标签 c++ c++11 arduino

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

我有一个 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/

相关文章:

c++ - 将内联函数作为参数传递

c++ - 如何将 zlib 流转换为 PNG?

c++ - SFINAE 启用/禁用功能和模板别名

c++ - 使用递归反向链表

audio - Arduino nano,声音检测

c++ - 在 C++ 中获取 iPhone 目录路径

c++ - 对象成员变量的意外更改

c++ - 从另一个部分特化的模板类继承部分特化的模板类

c - Sparkfun SC16IS750 中断引脚 IRQ 不工作

c++ - 开放框架/C++/Arduino : UDP SendAll fails at 1473 chars