[英]How to use a template function with multiple parameters in a template class C++
[英]C++ optimise class template function when template parameters identical
我有一個帶有模板方法的模板類,其中提供了兩個模板參數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”:非法使用顯式模板參數
因此,關於模板化類的模板成員的顯式專業化有些奇怪的事情。 看到這個問題 。
解決方法之一是使用助手類
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;
};
在這里可以找到更完整的示例
一種可能性是使用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>();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.