[英]Function template specialization in derived class
我有一個帶功能模板的基類。
我派生自基類,並嘗試在派生類中對函數模板進行專門化
我做了這樣的事。
class Base
{
..
template <typename T>
fun (T arg) { ... }
};
class Derived : public Base
{
...
} ;
template <>
Derived::fun(int arg);
在.cpp文件中,我提供了模板特化的實現。
這適用於MSVC 8.0和g ++ - 4.4.2抱怨Derived類中缺少函數聲明樂趣。
我不知道哪個編譯器的行為正確。 非常感謝任何幫助。
謝謝,蘇里亞
您需要在Derived中聲明該函數,以便能夠重載它:
class Derived : public Base
{
template <typename T>
void fun (T arg)
{
Base::fun<T>(arg);
}
} ;
template <>
void Derived::fun<int>(int arg)
{
// ...
}
請注意,您可能需要內聯特化或將其移動到實現文件,在這種情況下,您必須將頭文件中的特化原型設置為:
template <>
void Derived::fun<int>(int arg);
否則編譯器將使用通用版本的“fun”在調用代碼時生成代碼,而不是鏈接到特化。
你為什么不能這樣做
template <>
Base::fun(int arg);
g++
的錯誤信息對我來說很合適。 fun
在Base
聲明,而不是在Derived
。
g ++行為正確,因為fun在Base中定義。
此外,替代選項將是Derived中的普通非模板函數...
class Derived : public Base
{
public:
void fun(int) { /* ... */ }
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.