GirişBu yazıda iki tane amaç var
1. Template metodu bir parametre tipi için template kullanmadan overload etmek
2. Parametre tipine göre doğru template metodu seçmek
1. Template metodu bir parametre tipi için overload etmek
Örnek - Template Olmayan Overload
Non template functions are (let me say) preferred over function templates, thus you can easily got what you pay for in your code with an old plain function.
template <class T>
int HelloFunction(const T &a) {
std::cout << "Hello: " << a << std::endl;
return 0;
}
int HelloFunction(const char *a) {
std::cout << "Hello: " << a << std::endl;
return 0;
}
int main() {
HelloFunction(1);
HelloFunction("char");
return 0;
}
Template olan overload derlenmez! Elimizde şöyle bir kod
olsuntemplate <class T>
int HelloFunction(const T& a)
{
std::cout << "Hello: " << a << std::endl;
return 0;
}
template <>
int HelloFunction(const char* & a)
{
std::cout << "Hello: " << a << std::endl;
return 0;
}
int main()
{
HelloFunction(1);
HelloFunction("char");
return 0;
}
Bu kod derlenmez. İkinci HelloFunction için hata olarak şunu
alırız . Burada problem metod parametresinin generic tip olmaması.
error: template-id 'HelloFunction<>' for 'int HelloFunction(const char*&)' does not match
any template declaration
Eğer metod parametresi de generic tip olsaydı derlenirdi. Şu kod
derlenirtemplate<typename T>
struct ABC {
T type;
ABC(T inType) : type(inType) {}
};
template <class T>
int HelloFunction(ABC<T>& a)
{
std::cout << "Hello: " << a.type << std::endl;
return 0;
}
template <>
int HelloFunction(ABC<const char*> & a)
{
std::cout << "Hello: " << a.type << std::endl;
return 0;
}
int main()
{
HelloFunction(ABC<int>(1));
HelloFunction(ABC<const char*>("char"));
return 0;
}
Örnek
Şöyle
yaparız. Bu kodda T tipi parametre olarak kullanılıyor
template <class T>
T foo<T>(T val) { return someFunc(val); }
template <>
bool foo<bool>(bool val) { return otherFunc(val); };
Eğer foo metodunun Bar için derlenmemesini istersek şöyle
yaparız.
template <>
Bar foo<Bar>(Bar val) = delete;
Parametre tipine göre doğru template metodu seçmek