c++ - 通过模板检查是否存在带有参数列表的类成员函数?

标签 c++ templates c++17 sfinae

this question类似,是否可以使用SFINAE来确定类型是否具有带有特定参数的成员函数?如果没有其他问题回答的参数列表,则 std::void_t example表示效果很好。 (我与后者站在一起。)但是,如果我尝试使用额外的std::decltype<>()添加对参数lust的检查,则它会因template parameters not deducible in partial specialization而失败。有什么方法可以扩展此方法以检查某些参数类型吗?
示例代码:


#include <type_traits>

class A {
public :
    void a(){}
    void b(int val){}
};

class B {
public :
    void b(float val){}
};

// --- Has function a() without arguments

template <typename T, typename = void> struct has_a : std::false_type
{
};

template <typename T> struct has_a<T, std::void_t<decltype(std::declval<T>().a())>> : std::true_type
{
};

template <typename T> constexpr bool has_a_v = has_a<T>::value;

// This is OK:
static_assert(true == has_a_v<A>); 
static_assert(false == has_a_v<B>);

// --- Has function b() with one argument of one given type

template <typename T, typename U, typename = void> struct has_b : std::false_type
{
};

template <typename T ,typename U> struct has_b<T, std::void_t<decltype(std::declval<T>().b(std::declval<U>()))>> : std::true_type
{
};

template <typename T, typename U> constexpr bool has_b_v = has_b<T, U>::value;

// This fails with `template parameters not deducible in partial specialization`:
static_assert(true == has_b_v<A, int>);
static_assert(false == has_b_v<B, int>);

static_assert(false == has_b_v<A, float>);
static_assert(true == has_b_v<B, float>);

int main () { return 0;}

最佳答案

是。类void_t中的成员函数bB检查示例:

decltype( static_cast<void(B::*)(float)>(&B::b) )
这是如果您要检查准确的签名。您的方法也很好(一旦您按照问题下的注释修复它),但是实际上检查成员函数是否可以使用某些类型的参数进行调用(并忽略返回类型)。

关于c++ - 通过模板检查是否存在带有参数列表的类成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62554489/

相关文章:

c++ - 我的 ddwrt 路由器没有数据

templates - 使用 Modernizr 的网站/网页模板?

c++ - 其他成员函数的通用 'member function' 包装器?

C++ 剪切字符指针

c++ - 用位板识别棋子

c++ - 模板、接口(interface)(多重继承)和静态函数(命名构造函数)

C++:从单个 std::stringstream 转换多个命令行参数

c++ - 将临时地址传递给带有指针参数的函数是否合法

c++ - 哪个更快? "vector of structs"还是 "a number of vectors"?

templates - C++ for Rust 中特定模板用法的等价物