标准::enable_if的基本用法问题
Problem with basic usage of std::enable_if
我正在尝试制作一个简单的模板函数,给定一些参数,它输出它们时中间有一个空格。其中一些可以是枚举的元素,在这种情况下,我想输出其整数值。
这是我的代码:
#include <iostream>
#include <type_traits>
using std::cerr;
using std::endl;
// Output integer value if parameter is an element of an enum
template<typename T, typename = typename std::enable_if_t<std::is_enum<T>::value>>
constexpr std::ostream& debug(const T& a) {
cerr << (int)(a);
return cerr;
}
// Output parameter otherwise
template<typename T, typename = typename std::enable_if_t<!std::is_enum<T>::value>>
constexpr std::ostream& debug(const T& a) {
cerr << a;
return cerr;
}
// Print parameters separated by a space
template<typename T, typename ...U>
constexpr std::ostream& debug(const T& a, const U&... b) {
debug(a) << ' ';
debug(b...);
return cerr;
}
template<typename ...U>
constexpr void debug(const U&... a) {
debug(a...) << std::endl;
}
enum class Animal{Dog, Cat};
int main() {
debug(Animal::Dog);
debug(Animal::Dog, Animal::Cat);
debug("Hello");
debug(100, 'A');
debug(Animal::Dog, "Hello", "Bye");
}
注释最后三行,它说第二个函数是第一个函数的重新声明。关于如何解决此问题或为什么它不起作用的任何想法?
默认模板参数不是函数定义的一部分。请改用虚拟参数,以便第二个参数具有不同的类型:
template<typename T, typename std::enable_if_t<std::is_enum<T>::value, int> = 0>
constexpr std::ostream& debug(const T& a) {
std::cerr << (int)(a);
return std::cerr;
}
template<typename T, typename std::enable_if_t<!std::is_enum<T>::value, int> = 0>
constexpr std::ostream& debug(const T& a) {
std::cerr << a;
return std::cerr;
}
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 标准::enable_if的基本用法问题
- 基于智能指针的 CRTP 习惯用法的编译问题
- 这种result_of用法有什么问题?
- 语义问题 "Attempt to use a deleted function" 遇到使用 std::线程用法编译 c++ 代码
- Const用法——这里应该修改什么来修复这个问题
- 理解问题:预编译标头和包含用法
- 关于print用法的问题
- 关于C++中Typedef用法的问题