【问题标题】:Get template function type获取模板函数类型
【发布时间】:2013-08-20 11:27:04
【问题描述】:

我是在 C++ 中使用模板的新手,我想根据<> 之间使用的类型做不同的事情,所以function<int>()function<char>() 不会做同样的事情。 我怎样才能做到这一点?

template<typename T> T* function()
{
    if(/*T is int*/)
    {
        //...
    }
    if(/*T is char*/)
    {
        //...
    }
    return 0;
}

【问题讨论】:

  • 在你的情况下,T 不能从电话中推断出来,专业化是要走的路(正如答案所暗示的那样)。但是,如果您实际上在参数中使用T 并对其进行推断,则最好使用普通重载和avoiding function template specialisation

标签: c++ function templates c++11 types


【解决方案1】:

您想使用函数模板的显式特化:

template<class T> T* function() {
};

template<> int* function<int>() {
    // your int* function code here
};

template<> char* function<char>() {
    // your char* function code here
};

【讨论】:

  • 为什么不只是超载呢?重载通常比函数模板特化更可取。
  • 你不能只在返回值上重载
  • “为什么不只是过载?”只能重载参数类型,不能重载返回类型。
  • 对,没注意到参数中没有使用类型。
  • 专业化函数有点棘手。即使以额外输入为代价,我最好将函数分派到类模板(类模板中的静态成员函数)并在那里进行特化。
【解决方案2】:

创建template specializations

template<typename T> T* function()
{
 //general case general code
}

template<> int* function<int>()
{
  //specialization for int case.
}

template<> char* function<char>()
{
  //specialization for char case.
}

【讨论】:

  • @billz 。是的,你有编译器吗?显式指定模板参数的模板特化。
【解决方案3】:

最佳实践涉及标签调度,因为专业化很棘手。

标签调度更容易经常使用:

template<typename T>
T* only_if_int( std::true_type is_int )
{
  // code for T is int.
  // pass other variables that need to be changed/read above
}
T* only_if_int( std::false_type ) {return nullptr;}
template<typename T>
T* only_if_char( std::true_type is_char )
{
  // code for T is char.
  // pass other variables that need to be changed/read above
}
T* only_if_char( std::false_type ) {return nullptr;}
template<typename T> T* function()
{
  T* retval = only_if_int( std::is_same<T, int>() );
  if (retval) return retval;
  retval = only_if_char( std::is_same<T, char>() );
  return retval;
}

【讨论】:

  • 这个比较通用。但我不太理解“专业化很棘手”的部分。为什么这很棘手?您能否也将这部分添加到答案中。我可以将此答案作为参考吗?谢谢
  • @Kroushik 函数的专业化很棘手,因为它很容易出错!特化看起来有点像重载,但它不是重载,它按照不同的规则运行。超载和专业化的重叠可能会导致严重的脑筋急转弯“为什么这不起作用”问题。标签调度通过不专门化来避免这个问题,而是使用重载调度来完成这项工作,这减少了您需要记住的 C++ 标准的页数以了解会发生什么。
【解决方案4】:
template<class T>
T Add(T n1, T n2)
{
    T result;
    result = n1 + n2;

    return result;
}

要详细了解模板,请通过以下链接: http://www.codeproject.com/Articles/257589/An-Idiots-Guide-to-Cplusplus-Templates-Part-1

【讨论】:

    【解决方案5】:

    你可以像这样定义重载函数:

    #define INTT  0
    #define CHARR 1
    template<typename T>
    T* function()
    {
    int type;
    type = findtype(T);
    //do remaining things based on the return type
    
    }
    
    int findType(int a)
    {
    return INTT;
    }
    
    int findType(char a)
    {
    return CHARR;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 2011-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多