C++.可以做到这一点而不会出现错误:'未在此范围内声明'

dje*_*ent 0 c++ variables if-statement declaration

C++.是否有可能做到这一点?

if (x>3)
 int foo=10
else
 long foo=10
Run Code Online (Sandbox Code Playgroud)

没有得到错误:

在这方面没有申明

eml*_*lai 8

是的,你可以使用std::variantC++ 17boost::variant.

std::variant<int, long> foo;

if(x > 3)
    foo = 10;
else
    foo = long(10);
Run Code Online (Sandbox Code Playgroud)

然后访问foo如下:

if(auto value = std::get_if<int>(&foo))
    std::cout << "foo is int: " << *value << '\n'; 
else {
    long value = std::get<long>(foo);
    std::cout << "foo is long: " << value << '\n'; 
}
Run Code Online (Sandbox Code Playgroud)

我不知道你为什么要那样做.A long保证能够保存所有int值,因此您只需foo键入类型long,并std::variant完全避免.