Jas*_*n S 5 c++ templates reference
我有一个关于模板的问题,可以使用类或基本类型的参数.这是一些示例代码:
(注意:我的实际代码更复杂,下面的代码没用,但它重现了同样的问题)
template<typename T>
class Foo
{
T value;
public:
Foo() {}
const T& getValue() const { return value; }
Foo& setValue(const T& other) {
value = other; return *this;
}
};
struct Bar
{
int x;
Bar() : x(3) {}
};
int doit()
{
Foo<int> fooint;
Bar bar;
bar.x = 44;
Foo<Bar> foobar;
fooint.setValue(3); // warning here
foobar.setValue(bar);
int y = foobar.getValue().x + fooint.getValue();
return y;
}
Run Code Online (Sandbox Code Playgroud)
我得到一个编译器评论fooint.setValue():
value copied to temporary, reference to temporary used
Run Code Online (Sandbox Code Playgroud)
我理解这句话.我想知道Foo::setValue()如果我将Foo与原语和类/结构类型一起用作模板参数,我应该如何处理.
我认为setValue(const T& other)是通过引用传递常量类的正确方法签名.
有没有办法让setValue()所以它"做正确的事"既为Foo<int>和Foo<Bar>?
将临时数据绑定到const引用是完全合法的setValue().发布此评论的英特尔C++在这种情况下没有帮助.
编辑:我猜测TI编译器基于英特尔,对我来说,在该行上发布以下诊断:
test.cc(28): remark #383: value copied to temporary, reference to temporary used
fooint.setValue(3); // warning here
Run Code Online (Sandbox Code Playgroud)
该诊断在http://software.intel.com/en-us/articles/cdiag383/ 上进行了讨论
对于矢量的后推功能,可以安全地忽略此警告.向量将参数复制到自己的存储中; 它从不存储原始论点.因此,使用临时是非常安全的.
在您的情况下,您还要复制参数,因此也可以忽略它.