为每次处理特定类型的模板化函数提供多个实现

Providing multiple implementations for templated function tackling a particular type each time

本文关键字:函数 实现 处理 类型      更新时间:2023-10-16

我正在为字符串编写一个比较器。然而,我希望它同时适用于字符串和字符。类似于StringComparer<std::string, std::string>StringComparer<const char *, const char*>。当然,在Stringcomparer<const char *, const char *>的实现中,我将简单地为两个字符串执行std::string Stringversion(<pass the const char* here>),并简单地调用Stringcomparer<std::string, std::string>

如何为Stringcomparer编写两个这样的模板函数。

我一直在寻找这个,我在任何地方都能找到人们定义这样一个函数的例子:

template <typename T> foo(T&)
{
    //some operation on T that does depends on operators or functions that can handle any //type like sort or cout. basically there are showing that this fucntion can be used to sort //both integer and string vectors or it can cout both integers and floats.
}

你能告诉我如何提供我的字符串比较器的多种变体吗。当然,有时人们需要编写一个单独的例程来处理每种类型。这是怎么做到的。

您可以声明一个主函数模板,然后[完全]将其专门化为不同的类型,例如:

template <typename T> void foo(T&);                 // primary template declaration
template <> void foo<std::string>(std::string& s) { // specialization for std::string
    // ...
}
template <> void foo<char*>(char *&s) {             // specialization for char*
    // ...
}

请注意,专业化必须将主模板与完全替换的专业化类型相匹配!一般来说,我发现更容易专门化实现函数对象的类模板(即,具有函数调用运算符),并从通用函数模板委托给这些对象。

您可以使用模板专业化。下面是一个简短的例子。

template <typename T> 
void foo(const T& arg)
{
    // code
}
// Specialises the function template for char*
template <> 
void foo(const char*& arg)
{
    // different code
}

编辑:哦,专门为字符串开头。