如何使用enable_if基于类的模板参数启用成员函数 [英] How to use enable_if to enable member functions based on template parameter of class

查看:204
本文介绍了如何使用enable_if基于类的模板参数启用成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在代码中:

template<class T>
struct is_builtin
{
    enum {value = 0};
};

template<>
struct is_builtin<char>
{
    enum {value = 1};
};

template<>
struct is_builtin<int>
{
    enum {value = 1};
};

template<>
struct is_builtin<double>
{
    enum {value = 1};
};

template<class T>
struct My
{
    typename enable_if<is_builtin<T>::value,void>::type f(T arg)
    {
        std::cout << "Built-in as a param.\n";
    }


    typename enable_if<!is_builtin<T>::value,void>::type f(T arg)
    {
        std::cout << "Non - built-in as a param.\n";
    }
};

struct A
{
};

int main()
{
    A a;
    My<int> m;
    My<A> ma;
    m.f(1);
    ma.f(a);
    return 0;
}

我遇到错误:

error C2039: 'type' : is not a member of 'std::tr1::enable_if<_Test,_Type>'    

很明显,我不明白如何使用enable_if.我当时想的是,我可以在编译期间启用一组成员函数中的一个或第二个成员函数,但是它不起作用.任何人都可以向我解释如何正确执行此操作吗?
已编辑
我真正不明白的是,为什么其中一个def中没有typedef.编译器找不到它,也不会编译它.

Obviously I don't understand how to use enable_if. What I was thinking was that I can enable one or the second one member function from a set of member functions during compilation time but it does not work. Could anyone please explain to me how to do it correctly?
Edited
What I really can't understand is why isn't there typedef in one of those def. Compiler cannot find it and it wont compile it.

推荐答案

您不能使用类模板参数来获取成员函数的SFINAE.

You can't use class template parameters to get SFINAE for member functions.

您要么需要

  • 使成员函数成为成员函数模板,并在成员函数模板的模板参数上使用enable_if

将成员函数f移到策略类中,并使用enable_if专门化类模板.

move the member function f into a policy class and specialize the class template using enable_if.

这篇关于如何使用enable_if基于类的模板参数启用成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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