【问题标题】:Function template specialization in derived class派生类中的函数模板特化
【发布时间】:2010-12-28 01:01:10
【问题描述】:

我有一个带有函数模板的基类。

我从基类派生并尝试对派生类中的函数模板进行专门化

我做了这样的事情。

class Base 
{
..
template <typename T>
fun (T arg) { ... }

};

class Derived : public Base
{
...
} ;

template <>
Derived::fun(int arg);

在 .cpp 文件中,我提供了模板专业化的实现。

这适用于 MSVC 8.0,g++-4.4.2 抱怨 Derived 类中缺少函数声明乐趣。

我不知道哪个编译器的行为正确。非常感谢您提供任何帮助。

提前致谢, 苏里亚

【问题讨论】:

    标签: c++ inheritance templates


    【解决方案1】:

    你需要在 Derived 中声明函数才能重载它:

    class Derived : public Base
    {
        template <typename T>
        void fun (T arg) 
        {
            Base::fun<T>(arg);
        }
    
    } ;
    
    template <>
    void Derived::fun<int>(int arg)
    {
        // ...
    }
    

    请注意,您可能需要内联特化或将其移至实现文件,在这种情况下,您必须将头文件中的特化原型化为:

    template <>
    void Derived::fun<int>(int arg);
    

    否则编译器将在调用时使用“fun”的通用版本来生成代码,而不是链接到专业化。

    【讨论】:

    • Surya 试图做的事情有什么问题?我自己试过了,它没有编译。但我不明白为什么?
    • 在 Surya 的版本中没有名为“Derived::fun”的函数,只有“Base::fun”,所以不能专门化“Derived::fun”。
    【解决方案2】:

    你为什么不能这样做

    template <>
    Base::fun(int arg);
    

    g++ 的错误消息在我看来是正确的。 fun 是在 Base 中声明的,而不是在 Derived 中声明的。

    【讨论】:

      【解决方案3】:

      g++ 行为正确,因为 fun 是在 Base 中定义的。

      【讨论】:

        【解决方案4】:

        此外,另一种选择是 Derived 中的普通非模板函数...

        
        class Derived : public Base
        {
        public:
          void fun(int) { /* ... */ }
        };
        

        【讨论】:

        • 没那么简单,那会隐藏 Base::fun。
        猜你喜欢
        • 2016-09-26
        • 2018-01-22
        • 2017-02-10
        • 2014-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-16
        相关资源
        最近更新 更多