我有一个模板函数负责将模板值写入流中。它看起来像这样:模板函数:混合通过复制和传递参考
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”吗?
红利问题:如果我按照该顺序定义Write(int64)和Write(int32),那么Write(int64)会在我传递32位int时使用吗? – Takhiarel
@Takhiarel适用于超载的正常规则。如果传递一个32位'int',则将选择需要最少转换的过载(即如果存在一个,则为32位超载)。 – user3286380