[英]Partial template specialization on a class
我正在尋找一種更好的方法。 我有一大堆代碼需要處理包含不同類型的幾個不同對象。 我的結構看起來像這樣:
class Base
{
// some generic methods
}
template <typename T> class TypedBase : public Base
{
// common code with template specialization
private:
std::map<int,T> mapContainingSomeDataOfTypeT;
}
template <> class TypedBase<std::string> : public Base
{
// common code with template specialization
public:
void set( std::string ); // functions not needed for other types
std::string get();
private:
std::map<int,std::string> mapContainingSomeDataOfTypeT;
// some data not needed for other types
}
現在我需要添加一些僅適用於衍生類之一的附加功能。 特別是std :: string派生,但類型實際上並不重要。 這個課程足夠大,我寧願不復制整個東西只是為了專門化它的一小部分。 我需要添加一些函數(和訪問器和修飾符)並修改其他幾個函數的主體。 有沒有更好的方法來實現這一目標?
在模板定義中強加另一個間接層:
class Base
{
// Generic, non-type-specific code
};
template <typename T> class TypedRealBase : public Base
{
// common code for template
};
template <typename T> class TypedBase : public TypedRealBase<T>
{
// Inherit all the template functionality from TypedRealBase
// nothing more needed here
};
template <> class TypedBase<std::string> : public TypedRealBase<T>
{
// Inherit all the template functionality from TypedRealBase
// string-specific stuff here
}
你不必專門研究整個班級,只需要你想要的東西。 與GCC和MSVC合作:
#include <string>
#include <iostream>
class Base {};
template <typename T>
class TypedBase : public Base
{
public:
T get();
void set(T t);
};
// Non-specialized member function #1
template <typename T>
T TypedBase<T>::get()
{
return T();
}
// Non-specialized member function #2
template <typename T>
void TypedBase<T>::set(T t)
{
// Do whatever here
}
// Specialized member function
template <>
std::string TypedBase<std::string>::get()
{
return "Hello, world!";
}
int main(int argc, char** argv)
{
TypedBase<std::string> obj1;
TypedBase<double> obj2;
std::cout << obj1.get() << std::endl;
std::cout << obj2.get() << std::endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.