我如何使一个类只有编译时,它的类型有一个特定的成员函数? [英] How do I make a class that only compiles when its type has a certain member function?

查看:109
本文介绍了我如何使一个类只有编译时,它的类型有一个特定的成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 has_f 的类,我希望它只接受具有 f 成员函数的模板参数。我该怎么做?这是我试过的:

I have a class named has_f and I want it to only accept template parameters that have a f member function. How would I do that? This is what I tried:

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

template <typename T>
struct has_f<
    T,
     typename = typename std::enable_if<
        typename T::f
    >::type
> : std::true_type {};

但我得到一些神秘的错误。这是我想要使用的类:

But I get some cryptic errors. Here is the class I want to use:

struct A
{
    void f();
};

如何正确执行?谢谢。

推荐答案

从你的问题的标题,我假设你不需要一个类型从true_type或false_type - 只有当方法f不存在时才防止编译。如果是这种情况,如果你还需要一个特定的签名(至少在参数方面)的方法,在C ++ 11你可以这样做:

From the title of your question I presume that you don't really need a type deriving from true_type or false_type - only to prevent compilation if method f is not present. If that is the case, and if you also require a specific signature (at least in terms of arguments) for that method, in C++11 you can do something like this:

template <typename T>
struct compile_if_has_f
{
    static const size_t dummy = sizeof(
        std::add_pointer< decltype(((T*)nullptr)->f()) >::type );
};

这是f()不应该接受任何参数的情况。 std :: add_pointer只有在f返回void时才需要,因为sizeof(void)是非法的。

This is for the case when f() should not accept any arguments. std::add_pointer is only needed if f returns void, because sizeof(void) is illegal.

这篇关于我如何使一个类只有编译时,它的类型有一个特定的成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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