2010-01-27 89 views
2

我有一个模板类,里面有一个模板方法,给出两个模板参数T和U.该操作相当昂贵,并且在分析中显示为主要用途的CPU时间。我可以在某种程度上对其进行优化,但仅适用于T == U(这很常见)的情况,但我不确定这样做的语法...当模板参数相同时,C++优化类模板功能

问题中的类和方法看起来像这样的:

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

富::酒吧一般是从一些其他的模板代码调用,所以即使我创建了一个单独的方法(如“T fastBar()const的”)我不知道怎么的id去制作其他模板代码在可能的情况下调用该版本...

我试图为T == U创建明确的特化,但VC9给了我错误

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

错误C2768:“富::酒吧”:非法使用显式模板参数

回答

4

因此,有关于模板类的模板成员明确分工一些奇怪的事情。看到这个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; 

}; 

更完整的examnple可以发现here

+0

+1:嘿,我的编译,但没有链接:> – 2010-01-27 23:20:27

+0

它不那么怪异:你不能专注于成员f没有明确地专门化它们的封闭模板类,并且你不能部分地专门化函数 - 因此下一个最好的通用解决方案是将调用转发给部分专用类的成员函数。 – 2010-01-28 00:40:13

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>(); 
}