如何避免通用函数模板中的额外副本
How do I avoid the extra copy in the generic function template?
背景
我有一些用于持久性的通用代码,它使用boost::variant
来存储多种类型。在输出值时,我必须编写一个转换器函数protected_backslash_n
,在默认情况下,它什么都不做,但返回相同的值。
在模板参数为std::string
的特殊情况下,我使用boost::regex_replace()
搜索n
并将其替换为\n
。
问题
代码运行良好,但如果我能在通用情况下去掉额外的副本,那就太好了,因为值返回。
有没有一种方法可以做到这一点,同时允许专业的std::string
版本正常工作?
我尝试将返回值更改为T const&
,但专用版本无法匹配。
错误
GetPipedValues.hpp:15:21: error: template-id ‘protect_backslash_n<std::string>’ for ‘std::string pitbull::protect_backslash_n(const string&)’ does not match any template declaration
代码
template<typename T>
inline T protect_backslash_n( T const& orig )
{
return orig; // BAD: extra copy - how do I get rid of this?
}
template<>
inline std::string protect_backslash_n<std::string>( std::string const& orig )
{
boost::regex expr("(\n)");
std::string fmt("(\\n)");
return boost::regex_replace(
orig, expr, fmt, boost::match_default | boost::format_all
);
}
不要让它成为一个模板,而只是一个重载。如果参数匹配,编译器将选择该函数而不是模板实例化。
std::string protect_backslash_n( std::string const& orig);
这应该很简单:
template <typename T>
T const& protect_backslash_n(T const& orig)
{
return orig;
}
还有你拥有的std::string
版本。也许你需要额外的重载,例如获取一个非标准引用。在C++11中,该函数在默认情况下应模仿std::forward<T>
。
相关文章:
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 将重载的成员函数传递给函数模板
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?
- 具有常量引用参数的函数模板专用化
- std::span<const T> 作为函数模板中的参数
- 如何编写一个完美的缩写函数模板?
- 仅在函数模板中为那些定义了函数的类型执行函数
- 如何在C++中伪造虚拟可变参数函数模板?
- 以下代码中的函数模板有什么问题?
- 在 C++20 中是否不再允许在 std 中对程序定义类型的函数模板进行专用化?
- 将显式实例化的函数模板与转换匹配
- 使用定义函数模板别名
- 函数模板返回类型
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- C++ std::functional 中的可变参数函数模板
- 单行函数模板 c++ 的内联性保证
- C++函数模板需要 &for 数组参数
- 如何声明接受转发引用并返回引用或副本的函数模板
- 如何避免通用函数模板中的额外副本