是否有可能有一个“自动"?成员变量? [英] Is it possible to have an "auto" member variable?
问题描述
例如,我想要一个 auto
类型的变量,因为我不确定它是什么类型.
当我尝试在类/结构声明中声明它时,它给了我这个错误:
<块引用>无法推断自动类型.需要初始化程序
有办法解决吗?
struct Timer {自动开启;};
可以,但是必须声明static
和const
:
struct Timer {静态常量自动启动 = 0;};
由于此限制,您不能将 start
作为非静态成员,并且不能在不同的对象中具有不同的值.
如果你想为不同的对象使用不同类型的start
,最好将你的类作为模板
template结构定时器{开始;};
如果你想推导T
的类型,你可以制作一个类似工厂的函数来进行类型推导.
template定时器::type>MakeTimer(T&& startVal) {//转发参数return Timer::type>{std::forward(startVal)};}
实例.
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
Is there a way around it?
struct Timer {
auto start;
};
You can, but you have to declare it static
and const
:
struct Timer {
static const auto start = 0;
};
With this limitation, you therefore cannot have start
as a non-static member, and cannot have different values in different objects.
If you want different types of start
for different objects, better have your class as a template
template<typename T>
struct Timer {
T start;
};
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屋!