有没有一种方法可以专门针对目标图元的模板? [英] Is there a way to specialize a template to target primitives?

查看:35
本文介绍了有没有一种方法可以专门针对目标图元的模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在专门化类模板时,我希望有一个专门化目标全面的类(包括构造函数,析构函数等)和一个专门化目标原语( int float等).我看到的唯一的部分专业化是针对指针类型(通过 T * ).有办法吗?

In specializing a class template, I would like to have one specialization target full-blown classes (complete with constructor, destructor, etc.) and one specialization target primitives (int, float, etc.). The only partial specialization I've seen is with targeting pointer types (via T*). Is there a way to do this?

推荐答案

您可以使用C ++ 11 type_traits .以下是一些入门知识,您可以根据需要进行更多专业化设计:

You can used C++11 type_traits. Here is something to get you started, you can specialize more as needed:

#include <type_traits>
#include <iostream>

template<typename T, typename E = void>
struct A; // undefined

template<typename T>
struct A<T, typename std::enable_if<std::is_class<T>::value && !std::is_pod<T>::value>::type> {
        A() { std::cout << "I'm a class, but I'm not a pod type" << std::endl; }
};

template<typename T>
struct A<T, typename std::enable_if<std::is_class<T>::value && std::is_pod<T>::value>::type> {
        A() { std::cout << "I'm a class and a pod type" << std::endl; }
};

template<typename T>
struct A<T, typename std::enable_if<!std::is_class<T>::value>::type> {
        A() { std::cout << "I'm not a class" << std::endl; }
};

class X {};
class Y { ~Y(){} };

int main()
{
        A<X> a1;
        A<Y> a2;
        A<int> a3;
}

这篇关于有没有一种方法可以专门针对目标图元的模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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