Tak*_*rel 1 c++ templates pass-by-reference pass-by-value
我有一个模板函数,负责将模板值写入流.它看起来像这样:
template < typename T >
void Write( T value, std::ostream& stream, endianness_t endian );
Run Code Online (Sandbox Code Playgroud)
我已经实现了基本类型的版本:int,uint,float等.现在,如果我想编写一个更复杂的结构,比如一个std :: string,我就这样声明了:
template<>
inline void Write( const std::string& value, std::ostream& stream, endianness_t endian ) { // Notice the reference
...
}
Run Code Online (Sandbox Code Playgroud)
如果没有明确调用"pass-by-reference"版本,我就无法调用它:
Write( strValue, stream, LITTLE_ENDIAN ); // error : tries to call Write<std::string>, undefined
Write< const std::string& >( strValue, stream, LITTLE_ENDIAN ); // OK, Write<const std::string&> is properly defined
Run Code Online (Sandbox Code Playgroud)
问题在于,它对我想做的事情来说太冗长了.
那么我的问题是:如何让编译器猜测我想要使用的版本是"pass-by-reference"?
我是否必须更改模板函数以获取const引用?如果是这样,我可以专门研究是否对原始类型使用"pass-by-copy"?
您应该更喜欢重载模板专业化,这样做可以解决您的问题:
inline void Write( const std::string& value, std::ostream& stream, endianness_t endian ) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
我还建议您返回并更改您提到的所有专业知识,int并改为重载.