【发布时间】:2014-02-09 22:52:20
【问题描述】:
我有一个模板函数,负责将模板值写入流。它看起来像这样:
template < typename T >
void Write( T value, std::ostream& stream, endianness_t endian );
我已经实现了基本类型的版本:int、uint、float 等。 现在,如果我想写一个更复杂的结构,比如一个 std::string,我这样声明:
template<>
inline void Write( const std::string& value, std::ostream& stream, endianness_t endian ) { // Notice the 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
问题在于,它对于我想要做的事情来说太冗长了。
然后我的问题是:如何让编译器猜测我想要使用的版本是“按引用传递”的版本?
我是否必须更改我的模板函数以获取 const 引用?如果是这样,我可以专门针对原始类型使用“pass-by-copy”吗?
【问题讨论】:
标签: c++ templates pass-by-reference pass-by-value