使用类型谓词执行重载解析

Using type predicates to perform overload resolution?

本文关键字:重载 执行 谓词 类型      更新时间:2023-10-16

在c++ 14中,假设我有一组只有一个类型模板参数的N互斥bool constexpr变量模板:

template<typename T> constexpr bool P1 = ...;
template<typename T> constexpr bool P2 = ...;
.
.
.
template<typename T> constexpr bool PN = ...;

互斥是指对于任意两个不同的整数ij(在[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