检查类型 T 是否具有成员函数 SFINAE 的任何重载
Check if type T has any overloads of a member function, SFINAE
考虑以下内容,我想检查我传递给其他函数的类型是否sf
具有sf
所需的成员函数T::mf
,我知道返回类型和名称,但可以通过任意数量的重载。
经过一些修补(嗯,这很有趣.)和谷歌搜索,我可以让下面的代码工作,问题是我不知道如何表达print
可以有可变数量的参数。
#include <type_traits>
#include <utility>
template <typename T,typename = void>
struct has_write : std::false_type {};
template <typename T>
struct has_write<T, decltype(std::declval<T>().write())> : std::true_type {};
template <typename T, typename R = void , typename ...Args>
struct has_print : std::false_type {};
// cant deduce, specialization never used
template <typename T, typename ...Args>
struct has_print<T, decltype(std::declval<T>().print(std::declval<Args>()...))> : std::true_type {};
struct Foo {
void write();
};
struct Bar {
int print(int, float, int);
};
int main(){
static_assert(has_write<Foo>::value, "Does not have write..");
static_assert(has_print<Bar>::value, "Does not have print..");
return 0;
}
上面用g++
编译,但第二个assert
失败了,clang
更有帮助,告诉我has_print
的专业化永远不会被使用,因为它无法推断出所有类型。
由于您将从函数内部调用重载sf
因此您应该使用函数调用它的类型检查特定重载的可用性sf
该类型。
根据定义,一般检查类中任何重载的可用性始终是一个 XY 问题,因为任何重载的可用性从来都不重要。您需要知道您可以使用给定的参数集调用名称。考虑一下:请求给定名称的任何重载的可用性在概念上与询问特定类是否有任何方法相同。显然你不会对它感兴趣吗?
相关文章:
- 为什么使用SFINAE而不是函数重载
- 如何使用模板函数的函数签名进行SFINAE
- 编译器如何在使用SFINAE的函数和标准函数之间确定两者是否可行
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 基于 SFINAE 的特征实现问题与函数模板重载
- 函数模板实例化的 sfinae
- 使用表达式 SFINAE 的函数模板的类外定义
- C++SFINAE enable_if_t成员函数,如何消除歧义?
- 使用SFINAE来检测void返回类型函数的存在
- 构造函数SFINAE和继承在clang中失败
- 关于SFINAE的函数和结构之间的差异
- C++:SFINAE 来区分填充和范围构造函数?
- 使用 SFINAE 有选择地实例化模板的成员函数
- SFINAE 用于具有默认参数的函数对象
- SFINAE 和模板函数实例化:为什么在启用了 SFINAE 类型的函数参数中使用模板参数时无法推断模板参数?
- SFINAE :删除具有相同原型的函数
- 检查类型 T 是否具有成员函数 SFINAE 的任何重载
- SFINAE :知道一个函数是否已经存在
- Constexpr 函数作为 SFINAE 的模板参数
- 简单的 SFINAE 示例以重载函数不编译