如何为具有特定类型特征的所有类型编写函数模板? [英] How can I write a function template for all types with a particular type trait?

查看:103
本文介绍了如何为具有特定类型特征的所有类型编写函数模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例:

struct Scanner
{
    template <typename T>
    T get();
};

template <>
string Scanner::get()
{
    return string("string");
}

template <>
int Scanner::get()
{
    return 10;
}

int main()
{
    Scanner scanner;
    string s = scanner.get<string>();
    int i = scanner.get<int>();
}

Scanner类用于从某些来源提取令牌.上面的代码工作正常,但是当我尝试get其他整数类型(例如charunsigned int)时失败.读取这些类型的代码与读取int的代码完全相同.我可以复制我想阅读的所有其他整数类型的代码,但我想为所有整数类型定义一个函数模板.

The Scanner class is used to extract tokens from some source. The above code works fine, but fails when I try to get other integral types like a char or an unsigned int. The code to read these types is exactly the same as the code to read an int. I could just duplicate the code for all other integral types I'd like to read, but I'd rather define one function template for all integral types.

我尝试了以下操作:

struct Scanner
{
    template <typename T>
    typename enable_if<boost::is_integral<T>, T>::type get();
};

这像护身符一样工作,但是我不确定如何使Scanner::get<string>()再次起作用.那么,如何编写代码,以便可以执行scanner.get<string>()scanner.get<any integral type>()并具有单个定义来读取所有整数类型?

Which works like a charm, but I am unsure how to get Scanner::get<string>() to function again. So, how can I write code so that I can do scanner.get<string>() and scanner.get<any integral type>() and have a single definition to read all integral types?

更新:奖励问题:如果我想根据某些特征接受多个以上的课程,该怎么办?例如:如果我想拥有三个分别接受(i)整数类型(ii)浮点类型(iii)字符串的get函数,该如何解决这个问题.

Update: bonus question: What if I want to accept more than one range of classes based on some traits? For example: how should I approach this problem if I want to have three get functions that accept (i) integral types (ii) floating point types (iii) strings, respectively.

推荐答案

struct Scanner
{
    template <typename T>
    typename boost::enable_if<boost::is_integral<T>, T>::type get()
    {
        return 10;
    }
    template <typename T>
    typename boost::disable_if<boost::is_integral<T>, std::string>::type get()
    {
        return "string";
    }
};

更新如果我想基于某些特征接受多个范围的课程怎么办?"

struct Scanner
{
    template <typename T>
    typename boost::enable_if<boost::is_integral<T>, T>::type get()
    {
        return 10;
    }

    template <typename T>
    typename boost::enable_if<boost::is_floating_point<T>, T>::type get()
    {
        return 11.5;
    }

    template <typename T>
    std::string get(
          typename boost::disable_if<boost::is_floating_point<T>, T>::type* = 0, 
          typename boost::disable_if<boost::is_integral<T>, T>::type* = 0)

    {
        return std::string("string");
    }
};

这篇关于如何为具有特定类型特征的所有类型编写函数模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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