代码之家  ›  专栏  ›  技术社区  ›  uray

模板函数专用化默认参数

  •  2
  • uray  · 技术社区  · 16 年前
    template <typename T> void function(T arg1, 
        T min = std::numeric_limits<T>::min(),
        T max = std::numeric_limits<T>::max())
    {
    }
    
    template <> void function<int>(int arg1, int min,int max)
    {
    }
    
    int main(int argc,char* argv[])
    {
        function<int>(1);
    }
    

    它给出了函数默认参数行上的语法错误C2689和C2059 :: 但如果没有专业化,它做得很好。如果我改变默认参数 还在做专业化的工作:

    template <typename T> void function(T arg1, 
        T min = T(0),
        T max = T(1))
    {
    }
    template <> void function<int>(int arg1, int min,int max)
    {
    }
    

    问题也解决了。

    如果我这样用: function<int>(1,2,3); function<float>(1.0f) 很好,所以如果模板函数是专门化的,我们调用它时必须重写默认参数?

    但在我的第二个案子里 std::numeric_limits<T>::.. 具有 T(..) 调用时没有语法错误 function<int>(1)

    (我正在使用Visual Studio 2010 x64)

    由于最初的问题是因为bug,现在的问题改为 如何解决?

    3 回复  |  直到 16 年前
        1
  •  3
  •   James McNellis    16 年前

    代码没有问题;COMWONE,英特尔C++ 11.1,G++4.1.2编译成功。

    我猜这是编译器中的一个bug。我最近提交了一个相关的,但略有不同 bug report 针对Visual C++ 2010编译器。


    作为一种解决方法,您可以包装调用:

    template <typename T>
    T get_limits_min() { return std::numeric_limits<T>::min(); }
    
    template <typename T>
    T get_limits_max() { return std::numeric_limits<T>::max(); }
    
    template <typename T> void function(T arg1, 
        T min = get_limits_min<T>(),
        T max = get_limits_max<T>())
    {
    }
    

    丑陋?完全正确。


    我贴了以下回复 the bug you reported on Microsoft Connect:

    主模板必须具有具有默认参数值的参数。默认参数值必须是不在全局命名空间中的类模板的成员函数。

    以下是要复制的最小代码:

    namespace N
    {
        template <typename T>
        struct S
        {
            static T g() { return T(); }
        };
    }
    
    template <typename T> void f(T = N::S<T>::g()) { }
    
    template <> void f<>(int) { }
    
    int main()
    {
        f<int>();
    }
    

    error C2589: '::' : illegal token on right side of '::'
    error C2059: syntax error : '::'
    

    有趣的是,如果类模板位于全局命名空间中,还有另一个问题。给定以下代码:

    template <typename T>
    struct S
    {
        static T g() { return T(); }
    };
    
    template <typename T> void f(T = ::S<T>::g()) { }
    
    template <> void f<>(int) { }
    
    int main()
    {
        f<int>();
    }
    

    error C2064: term does not evaluate to a function taking 0 arguments
    

    这两个示例测试用例都是格式良好的C++程序。

        2
  •  2
  •   Community Mohan Dere    9 年前

    正如在这里回答的 https://stackoverflow.com/a/13566433/364084 https://stackoverflow.com/a/27443191/364084

    template <typename T> void function(T arg1, 
        T min = (std::numeric_limits<T>::min)(),
        T max = (std::numeric_limits<T>::max)())
    {
    }
    
    template <> void function<int>(int arg1, int min,int max)
    {
    }
    
    int main(int argc,char* argv[])
    {
        function<int>(1);
    }
    
        3
  •  0
  •   BE Student BE Student    16 年前

    在里面 科莫在线, http://codepad.org,EDG