是否可以拥有"自动"成员变量?

Ole*_*siy 15 c++ struct auto

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

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

无法推断自动类型.需要初始化程序

有办法解决吗?

struct Timer {

    auto start;

};
Run Code Online (Sandbox Code Playgroud)

Mar*_*cia 24

你可以,但你必须声明它static并const:

struct Timer {
    static const auto start = 0;
};
Run Code Online (Sandbox Code Playgroud)

科利鲁的一个工作实例.

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

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

template<typename T>
struct Timer {
    T start;
};
Run Code Online (Sandbox Code Playgroud)

如果你想推断出类型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)};
}
Run Code Online (Sandbox Code Playgroud)

实例.


And*_*een 6

如果在 lambda 表达式中声明类,则可以使用以下方式推断成员变量的类型decltype:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

auto generic_class = [](auto width1, auto height1) {
    class local_class {
        public:
        decltype(width1) width;
        decltype(height1) height;
    } local;
    local.width = width1;
    local.height = height1;
    return local;
};

int main()
{
    auto obj1 = generic_class(3,std::string("Hello!"));
    auto obj2 = generic_class(std::vector<int>{1,2},true);
    cout << obj1.height << "\n";
    cout << obj2.width[0] << "\n";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Sha*_*our 5

这就是C++ 草案标准关于使用auto成员变量的说法,在章节7.1.6.4 auto specifier段落中4:

auto 类型说明符也可用于在选择语句 (6.4) 或迭代语句 (6.5) 的条件中声明变量,在 new-type-id 或 type-id 的 type-specifier-seq 中new 表达式 (5.3.4),在 for-range-declaration 中,并在声明一个静态数据成员时使用一个出现在类定义的 member-specification 中的括号或等号初始化器 (9.4.2) .

由于它必须被初始化,这也意味着它必须是const. 因此,类似以下内容将起作用:

struct Timer
{
  const static int start = 1;
}; 
Run Code Online (Sandbox Code Playgroud)

不过,我认为这不会让你太过分。按照 Mark 的建议使用模板,或者现在我再考虑一下,也许您只需要一个变体类型。在这种情况下,您应该查看Boost.Variant或Boost.Any。