是否有可能具有“自动"功能?成员变量? [英] Is it possible to have an "auto" member variable?
问题描述
例如,我想拥有类型为auto
的变量,因为我不确定它将是哪种类型.
For example I wanted to have a variable of type auto
because I'm not sure what type it will be.
当我尝试在类/结构声明中声明它时,出现此错误:
When I try to declare it in class/struct declaration it's giving me this error:
无法推断自动类型.需要初始化器
Cannot deduce auto type. Initializer required
有办法解决吗?
struct Timer {
auto start;
};
推荐答案
可以,但是必须声明static
和const
:
You can, but you have to declare it static
and const
:
struct Timer {
static const auto start = 0;
};
因此,使用此限制,您不能将start
作为非静态成员,并且在不同的对象中不能具有不同的值.
With this limitation, you therefore cannot have start
as a non-static member, and cannot have different values in different objects.
如果要为不同的对象使用不同类型的start
,最好将类作为模板
If you want different types of start
for different objects, better have your class as a template
template<typename T>
struct Timer {
T start;
};
如果要推导T
的类型,则可以制作一个类似于工厂的函数来进行类型推导.
If you want to deduce the type of T
, you can make a factory-like function that does the type deduction.
template<typename T>
Timer<typename std::decay<T>::type> MakeTimer(T&& startVal) { // Forwards the parameter
return Timer<typename std::decay<T>::type>{std::forward<T>(startVal)};
}
在线示例.
这篇关于是否有可能具有“自动"功能?成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!