为每次处理特定类型的模板化函数提供多个实现
Providing multiple implementations for templated function tackling a particular type each time
我正在为字符串编写一个比较器。然而,我希望它同时适用于字符串和字符。类似于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
}
编辑:哦,专门为字符串开头。
相关文章:
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 分段 排序函数实现中的错误
- 无法去函数实现 vim
- C++ 20 中的运算符 == 和 <=> 应该作为成员还是自由函数实现?
- 为什么在这种情况下不调用我的虚拟函数实现?
- 我能否通过将函数实现为类对象方法来避免使用互斥锁
- 嵌套的模板结构构造函数实现
- C++接口的工厂函数实现
- 链表中的递归长度函数实现
- 我可以期望某些 STL 函数实现是可自动矢量化的吗?
- 如何将深拷贝构造函数实现到链表中?
- 虚拟 CTOR 的克隆函数实现是否有问题
- 没有捕获列表的 lambda 通常作为普通函数实现吗?
- C++二叉树打印函数实现
- C++:默认构造函数实现
- C++派生类中的纯虚函数实现
- 决定放置函数实现的位置
- 强制实施纯虚函数实现,可能使用不同的参数类型
- 如何让成员函数实现依赖于类的模板参数?
- 我们如何将Ostream函数作为类的成员函数实现,而不是作为朋友函数,以便我可以用作虚拟函数