【问题标题】:C++ optimise class template function when template parameters identical当模板参数相同时,C ++优化类模板函数
【发布时间】:2010-01-27 22:55:00
【问题描述】:

我有一个模板类,其中包含一个模板方法,提供两个模板参数 T 和 U。该操作非常昂贵,并且在分析中显示为 CPU 时间的主要用途。我可以对其进行一些优化,但仅限于 T == U 的情况(这是相当常见的),但是我不确定这样做的语法......

有问题的类和方法如下所示:

template<typename T>class Foo
{
public:
    ...
    template<typename U>U bar()const;
};

Foo::bar 通常是从其他模板代码调用的,所以即使我创建了一个单独的方法(例如“T fastBar()const”),我也不知道 id 如何让其他模板代码调用它尽可能的版本...

我尝试为 T == U 创建显式特化,但 VC9 给了我错误

template<typename T>template<>T Foo<T>::bar<T>()const

错误 C2768: 'Foo::bar' : 非法使用显式模板参数

【问题讨论】:

    标签: c++ optimization templates template-specialization


    【解决方案1】:

    因此,模板类的模板成员的显式特化有一些奇怪的事情。看到这个question

    一种解决方法是使用辅助类

    template< typename T, typename U>
    struct FooDispatchHelper
    {
       static U dispatch( const Foo<T> * f )
       {
         return f->template bar_internal<U>();
       }
    };
    
    template< typename T >
    struct FooDispatchHelper<T,T>
    {
       static T dispatch( const Foo<T> * f )
       {
         return f->bar_fast();
       }
    };
    
    template<typename T>class Foo
    {
    public:
    ...
       template<typename U>U bar() const
       {
          return FooDispatchHelper<T,U>::dispatch( this );
       }
    
      template<typename U> U bar_internal() const;
      T bar_fast() const;
    
    };
    

    更完整的例子可以找到here

    【讨论】:

    • 这并不奇怪:如果没有明确地特化它们的封闭模板类,你就不能特化成员函数,你也不能部分特化函数——因此,下一个最好的通用解决方案是将调用转发到部分专业课。
    【解决方案2】:

    一种可能性是使用boost::enable_if / disable_if 来选择可用于特定实例化的版本:

    #include <iostream>
    #include <boost/utility/enable_if.hpp>
    #include <boost/type_traits.hpp>
    
    template <class T>
    class Foo
    {
    public:
        template <class U>
        typename boost::disable_if<boost::is_same<T, U>, U>::type bar() const
        { std::cout << "Different U\n"; return U(); }
    
        template <class U>
        typename boost::enable_if<boost::is_same<T, U>, U>::type bar() const
        { std::cout << "Same U\n"; return U(); }
    };
    
    
    int main()
    {
        Foo<int> f;
        f.bar<int>();
        f.bar<float>();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多