使用类型谓词执行重载解析
Using type predicates to perform overload resolution?
在c++ 14中,假设我有一组只有一个类型模板参数的N
互斥bool constexpr变量模板:
template<typename T> constexpr bool P1 = ...;
template<typename T> constexpr bool P2 = ...;
.
.
.
template<typename T> constexpr bool PN = ...;
互斥是指对于任意两个不同的整数i
和j
(在[1..N]
中)和任意类型T, Pi<T> && Pj<T>
为假。
我想定义一个由N
函数定义组成的单形参的重载函数集,这样,如果Pi<T>
为真,具有T类型参数的函数调用表达式将选择ith
函数,如果没有这样的Pi
,则将无法编译:
void f(T such that P1<T>) { defn1; }
void f(T such that P2<T>) { defn2; }
.
.
.
void f(T such that PN<T>) { defnN; }
实现这个最简单的方法是什么?
您可以使用SFINAE:
template <typename T>
std::enable_if_t<P1<T>>
f(const T&t) { defn1(); }
template <typename T>
std::enable_if_t<P2<T>>
f(const T&t) { defn2(); }
// ...
要求对于类型T
,只有一个Pi<T>
是true
。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 继承函数的重载解析
- C++,系统无法执行指定的程序
- 你能重载对象变量名本身返回的内容吗
- 从父命名空间重载类型
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 使用重载运算符在函数调用时执行操作
- 正确执行运算符重载和多态性
- 如何重载iostream运算符以在整个流上执行功能
- 对重载运算符参数执行隐式转换时出现编译器错误
- 无法弄清楚为什么使用重载比较运算符在执行前调用复制构造函数
- 赋值重载显式调用析构函数(在执行其他二进制重载运算符之后)
- 执行重载构造函数的原因和时间
- 使用类型谓词执行重载解析
- 为什么操作符重载不能正常执行
- 重载<<和>>C++以执行小数移位
- 如何在c++中执行操作符重载以避免if条件
- 重载函数和可执行文件/库的大小
- 构造函数和重载运算符执行顺序