【问题标题】:What are the uses of default function template arguments默认函数模板参数的用途是什么
【发布时间】:2015-09-04 09:51:26
【问题描述】:

class 模板参数不同,模板参数必须由模板的用户指定,function 模板参数由编译器推导出。因此,一个自然的问题出现了:为什么要指定 default 函数模板参数?

我能想到的一种用法是当我们想要强制一些函数模板参数而不需要指定所有参数时。然而,这似乎是一个极端情况。还有其他情况吗?

【问题讨论】:

  • “函数模板参数由编译器推导出来”。 Or not.
  • 发布时我正在写回复:)

标签: c++11 function-templates


【解决方案1】:

这可能是部分答案。我想到的一种用途是当我们有一个模板参数没有作为类型出现在函数的参数列表中,因此无法推断。为该模板参数提供默认参数可能非常合理。上述评论来自 n.m.提供了这种用法的一个很好的例子。

【讨论】:

    【解决方案2】:

    尝试将下面的func 转换为constructor(它们没有返回类型)。

      template<class T>
      typename std::enable_if< std::is_fundamental<T>::value >::type func(T p_arg){}
    
      template<class T>
      typename std::enable_if< !std::is_fundamental<T>::value >::type func(T const &p_arg){}
    

    使用默认函数模板参数非常简单。

    【讨论】:

    • 我不太清楚您要完成什么。你能帮我用代码跟进最后一句话吗?
    【解决方案3】:

    例子:

     template <typename Y, typename Y, int Z>
     class Do{};
    

    X,Y,Z 是模板参数。

    用户可以这样使用:

     Do<int,int,1> doit;
    

    在使用类模板时,无法从函数参数中推导出模板参数。

    你称之为“默认”参数...

     template <typename Y, typename Y, int Z=9>
     class Do{};
    

    如果使用代码中没有给出任何内容,则此处 Z 默认为 9:

    Do<int,int> doit;
    

    如果您的模板参数可以从函数参数中推导出来,用户可能希望使用特殊的模板实例,例如:

    template <typename T>
    void func( const T&);
    
        template<>
    void func( const int& )
    {   
        std::cout << "int in use" << std::endl;
    }   
    
    template<>
    void func( const double&)
    {   
        std::cout << "double in use" << std::endl;
    }   
    
    int main()
    {   
        func(3.4); // calls double
        func<int>(3.4); //calls int
    } 
    

    【讨论】:

    • 问题是关于 function 模板。
    • 非常感谢!手动给定参数的示例与函数模板完全相同!并且将它用于类或函数模板在这里是一样的......没关系!玩得开心:-)
    猜你喜欢
    • 2017-04-10
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    相关资源
    最近更新 更多