C ++-使用decltype或auto创建一个临时对象 [英] C++ - Creating a temporary object with decltype or auto
本文介绍了C ++-使用decltype或auto创建一个临时对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象"a",我想将其复制到对象"b"中,但对其进行一些修改而不修改"a".然后看起来像这样:
I have an object "a" and I want to copy it into an object "b" but modify it a bit without modifying "a". Then that would look like this:
class SomeClass{
public:
int a;
public:
SomeClass(int _a) {a = _a;}
SomeClass& doStuff() {++a; return *this;}
};
const SomeClass a( 25);
const auto b = SomeClass( a).doStuff();
这很好用,但是可以说我现在/不想写"a"的类型,然后我想出了以下解决方案:
This works nice but lets say I don't now / don't want to write the type of "a", then I came up with this solution:
const auto b = std::remove_const<decltype( a)>::type( a).doStuff();
我这样做正确吗?是否有一个不太丑陋的解决方案?(在这里我不必两次键入"a".)使用auto或其他方法.最好不是宏.
Am I doing this right? Is there a less ugly solution for this? (where I don't have to type "a" twice.) Using auto or something. Preferably not a macro.
推荐答案
如何
template<typename T>
T copy(const T& t) { return T(t); }
const auto b = copy(a).doStuff();
这篇关于C ++-使用decltype或auto创建一个临时对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文