检测c++模板元编程中的void方法 [英] Detecting void method in c++ template metaprogramming

查看:25
本文介绍了检测c++模板元编程中的void方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个模板元函数来检测一个类型是否有一个 void 类型的成员函数.

I am trying to write a template metafunction to detect if a type has a member function with void type.

目前我可以使用 SFINAE 来检测成员函数是否具有明确的类型,例如 double、int 等.使用类似

Currently I am able to use SFINAE to detect if a member function has a definite type such as double, int, etc. using something like

 template<typename C> static auto Test(void*) -> decltype(int{std::declval<C>().foo()}, Yes{});

当然我可以反转它(如附加的代码片段所示)来测试它不是 int,但我无法弄清楚如何测试它是无效的.

And of course I can invert that (as shown in the attached code snippet) to test that it is not int, but I am unable to figure out how to test that it is void.

下面的代码片段当前输出

The code snippet below currently outputs

A  does not have void foo
B  has void foo
C  has void foo

但是,C 的 foo() 方法的类型为 double,因此这是不正确的输出.如何调整它以正确检查 void foo()?

However, C's foo() method has type double, and thus this is the incorrect output. How can I adjust it to correctly check for a void foo()?

#include <iostream>
#include <memory>

class A {
public:
    int foo() {
        return 0;
    }
};

class B {
public:
    void foo() {
    }
};

class C {
public:
    double foo() {
        return 0;
    }
};

template <typename T>
class has_void_foo {
private:
  typedef char Yes;
  typedef Yes No[2];

  template<typename C> static auto Test(void*) -> decltype(int{std::declval<C>().foo()}, Yes{});
  template<typename> static No& Test(...);

public:
    static bool const value = sizeof(Test<T>(0)) != sizeof(Yes);
};

int main(void) {
    std::cout << "A ";
    if (has_void_foo<A>::value) {
        std::cout << " has void foo";
    } else {
        std::cout << " does not have void foo";
    }
    std::cout << std::endl << "B ";
    if (has_void_foo<B>::value) {
        std::cout << " has void foo";
    } else {
        std::cout << " does not have void foo";
    }
    std::cout << std::endl << "C ";
    if (has_void_foo<C>::value) {
        std::cout << " has void foo";
    } else {
        std::cout << " does not have void foo";
    }
    std::cout << std::endl;

    return 0;
}

推荐答案

它遵循一个基于 constexpr 函数的可能解决方案:

It follows a possible solution based on a constexpr function:

#include <type_traits>

struct A {
    int foo() {
        return 0;
    }
};

struct B {
    void foo() {
    }
};

struct C {
    double foo() {
        return 0;
    }
};

template<typename T, typename R, typename... Args>
constexpr bool has_void_foo(R(T::*)(Args...)) { return std::is_void<R>::value; }

int main() {
    static_assert(not has_void_foo(&A::foo), "!");
    static_assert(has_void_foo(&B::foo), "!");
    static_assert(not has_void_foo(&C::foo), "!");
}

这篇关于检测c++模板元编程中的void方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆