gpt4 book ai didi

c++ - 模板函数 : mixing pass-by-copy & pass-by-reference

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:15:34 27 4
gpt4 key购买 nike

我有一个模板函数,负责将模板值写入流。它看起来像这样:

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 引用?如果是这样,我是否可以专门针对原始类型使用“复制传递”?

最佳答案

你应该更喜欢重载而不是模板特化,我认为这样做可以解决你的问题:

inline void Write( const std::string& value, std::ostream& stream, endianness_t endian ) {
// ...
}

我还建议您返回并将您提到的所有针对 int 的特化和内容更改为重载。

关于c++ - 模板函数 : mixing pass-by-copy & pass-by-reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21666212/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com