【问题标题】:Specializing member function template of a non-template class特化非模板类的成员函数模板
【发布时间】:2014-01-13 11:58:19
【问题描述】:

成员函数模板bar 的以下特化是否有效?它在 gcc 4.5.3 和 VS .NET 2008 上编译。我很困惑,因为我隐约记得读过函数模板不能专门化。

struct Foo
{
    template<typename T>
    void bar();
};

template<typename T>
void Foo::bar(){}

template<>
void Foo::bar<bool>(){}

int main()
{
    Foo f;
    f.bar<char>();
    f.bar<bool>();
}

【问题讨论】:

    标签: c++ templates template-specialization overloading function-templates


    【解决方案1】:

    函数模板不能部分特化,但可以显式特化,你的代码完全正确。

    【讨论】:

      【解决方案2】:

      函数模板偏特化was considered in C++11 but was rejected 因为函数模板重载可以用来解决同样的问题。但是,执行此操作时必须查找 some caveats

      例子:

      template <typename T> void foo(T);
      void foo(int);
      
      foo(10);   // calls void bar(int)
      foo(10.f); // calls void bar(T) [with T = float]
      foo(10u);  // calls void bar(T) [with T = unsigned int]!!
      

      对于你的情况,这种方法可能有用

      struct Foo
      {
          template<typename T>
          void bar(T dummy);
      
          void bar(bool dummy);
      };
      
      template<typename T>
      void Foo::bar(T dummy) { }
      
      void Foo::bar(bool dummy) { }
      
      int main()
      {
          Foo f;
          f.bar('a');
          f.bar(true);
      }
      

      【讨论】:

        猜你喜欢
        • 2013-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-03
        • 2023-01-10
        相关资源
        最近更新 更多