模板检测 T 是指针还是类 [英] Template detects if T is pointer or class

查看:20
本文介绍了模板检测 T 是指针还是类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

class MyClass
{
    ...
};

template <typename Object>
class List
{
public:

    void insert(const Object & x)
    {
        // call when Object is MyClass
    }

    void insert(const Object & x)
    {
        // call when Object is MyClass*
    }
}

int main()
{
    MyClass a;

    List<MyClass> lst;
    List<MyClass*> plst;

    lst.insert(a);
    plst.insert(new Myclass);

    return 0;
}

如何根据模板是类还是指针来告诉编译器调用不同的方法?

How to tell the compiler call different methods based on if the template is a class or a pointer?

如何修复上面的代码?

推荐答案

您可以结合使用 std::is_pointerstd::enable_if:

You can use a combination of std::is_pointer and std::enable_if:

#include <type_traits>
#include <iostream>

class MyClass
{
};

template <typename Object>
class List
{
public:

    template<class T=Object>
    void insert(T t, typename std::enable_if<std::is_pointer<T>::value >::type* = 0) 
    {
        std::cout << "insert pointer" << std::endl;
    }

    template<class T=Object>
    void insert(T t, typename std::enable_if<!std::is_pointer<T>::value >::type* = 0) 
    {
        std::cout << "insert non-pointer" << std::endl;
    }
};

int main()
{
    MyClass a;

    List<MyClass> lst;
    List<MyClass*> plst;

    lst.insert(a);
    plst.insert(new MyClass());

    return 0;
}

现场示例:https://ideone.com/CK8Zdo

这将允许您将指针和非指针都插入到指针或非指针列表中.如果你想限制它,你可以使用这个:

This will allow you to insert both pointers and non-pointers into a pointer or non-pointer list. If you want to restrict that, you can use this:

#include <type_traits>
#include <iostream>
class MyClass
{
};

template <typename Object>
class List
{
public:

    template<class T=Object>
    void insert(T t, typename std::enable_if<std::is_same<T,Object>::value&&std::is_pointer<T>::value >::type* = 0) 
    {
        std::cout << "insert pointer" << std::endl;
    }

    template<class T=Object>
    void insert(const T& t, typename std::enable_if<std::is_same<T,Object>::value&&!std::is_pointer<T>::value >::type* = 0) 
    {
        std::cout << "insert non-pointer" << std::endl;
    }
};

int main()
{
    MyClass a;

    List<MyClass> lst;
    List<MyClass*> plst;

    lst.insert(a);
    // plst.insert(a); // compiler error

    // lst.insert(new MyClass()); // compiler error
    plst.insert(new MyClass());


    return 0;
}

现场示例:https://ideone.com/3DtBfr

这篇关于模板检测 T 是指针还是类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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