gpt4 book ai didi

c++ - 是否可以有一个 "auto"成员变量?

转载 作者:IT老高 更新时间:2023-10-28 22:25:06 27 4
gpt4 key购买 nike

例如,我想要一个 auto 类型的变量,因为我不确定它是什么类型。

当我尝试在类/结构声明中声明它时,它给了我这个错误:

Cannot deduce auto type. Initializer required

有办法解决吗?

struct Timer {

auto start;

};

最佳答案

可以,但必须声明 staticconst:

struct Timer {
static const auto start = 0;
};

A working example in Coliru .

由于此限制,您因此不能将 start 作为非静态成员,并且不能在不同对象中具有不同的值。

如果你想要不同类型的 start 用于不同的对象,最好将你的类作为模板

template<typename T>
struct Timer {
T start;
};

如果你想推断T的类型,你可以做一个类似工厂的函数来做类型推断。

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)};
}

Live example .

关于c++ - 是否可以有一个 "auto"成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18199728/

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