[英]How do you specialize a templated method with no parameters in a non-templated class?
我試圖在非模板化的類中專門化一個模板化方法,其中方法的返回類型包括模板化類型 - 此方法不帶參數。 我一直在尋找並嘗試通過反復試驗來編譯,但無濟於事。
如何構建此代碼? 這種語法甚至可能嗎? (我試圖專門化的模板化方法是cBar::getFoos
,如下面的評論所示。)
下面的簡化示例代碼:
#include <vector>
////////////////////////////////////////////////////////////////////////////////
// the non-templated class below contains std::vector objects of these types
// (tBuiltInType is an int, float, or bool - but hopefully that's not an
// assumption that needs to be made, as I'd like to include more complex types)
template< typename tBuiltInType >
class cFoo
{
public:
// ...
void doSomething()
{
// ... (unimportant what happens here, but stuff happens)
}
private:
std::vector< tBuiltInType > m_objects;
};
////////////////////////////////////////////////////////////////////////////////
// this contains the templated method I'm trying to specialize - getFoos
class cBar
{
public:
// ...
// this is the method I'm trying to specialize by contained type (see private area)
// getFoos< int >() would return m_intFoos, etc.
template< typename tBuiltInType >
std::vector< cFoo< tBuiltInType > > &getFoos();
// (probably unimportant) example use
template< typename tBuiltInType >
void doSomething()
{
for ( cFoo< tBuiltInType > &foo : getFoos< tBuiltInType >() )
foo.doSomething();
}
private:
std::vector< cFoo< int > > m_intFoos;
std::vector< cFoo< bool > > m_boolFoos;
std::vector< cFoo< float > > m_floatFoos;
};
////////////////////////////////////////////////////////////////////////////////
// some (also probably unimportant) example usage code
int main()
{
cBar bar;
bar.doSomething< int >();
bar.doSomething< bool >();
bar.doSomething< float >();
return 0;
}
(我正在拜訪我的家人,沒有筆記本電腦,所以我通常的開發設置不可用 - 我可以發布我嘗試過的在線編譯器的錯誤,但我懷疑它在這里做得很好,因為沒有很多人會看到一個神秘的在線編譯器錯誤,並知道該怎么做,所以為了壓縮問題文本,我會跳過那一點。)
所以你想讓getFoos<int>()
返回m_intFoos
等? 我認為最簡單的方法是引入一個空的tag-dispatch類型:
template <typename T> struct empty { };
template< typename tBuiltInType >
std::vector< cFoo< tBuiltInType > >& getFoos()
{
return getFoosImpl(empty<tBuiltInType>{} );
}
然后提供正確的重載:
std::vector< cFoo<int> >& getFoosImpl(empty<int> ) { return m_intFoos; }
std::vector< cFoo<bool> >& getFoosImpl(empty<bool> ) { return m_boolFoos; }
std::vector< cFoo<float> >& getFoosImpl(empty<float> ) { return m_floatFoos; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.