有没有办法一次声明相同类型的多个对象,并通过一个表达式立即使用相同的右值初始化它们?

Is there a way to declare multiple objects of the same type at once and initialize them immediately with the same rvalue by just one expression?

本文关键字:表达式 初始化 一个 一次 声明 同类型 有没有 对象      更新时间:2023-10-16

我想声明多个相同类型的对象,并通过一个表达式使用相同的右值初始化它们;而不需要通过单独的语句声明和初始化它们。

我想要的是这样的:

int a = b = 10;  // dummy-statement. This does not work.

int a = int b = 10; // dummy-statement. This does not work either.

而不是

int b = 10;
int a = b;

有没有办法做到这一点?

从技术上讲,是的:int a = value, b = a;,或者你可以考虑int a, b = a = value;。不重复标识符,不,至少在 C 中没有;语法根本没有规定。语法中的每个">声明符=初始值设定项"只能声明一个对象,根据 C 2018 6.7.6 1 中的语法生成和 6.7.6 2 中的显式语句:"每个声明符声明一个标识符...">

正如评论中提到的,这是一种可怕的C++方法。我不对C++关于单个声明中初始化顺序的规则、线程问题等做出任何陈述。这仅作为教育活动呈现。切勿在生产代码中使用它。

template<class T> class Sticky
{
private:
static T LastInitializer;   //  To remember last explicit initializer.
T Value;                    //  Actual value of this object.
public:
//  Construct from explicit initializer.
Sticky<T>(T InitialValue) : Value(InitialValue)
{ LastInitializer = InitialValue; }
//  Construct without initializer.
Sticky<T>() : Value(LastInitializer) {}
//  Act as a T by returning const and non-const references to the value.
operator const T &() const { return this->Value; }
operator T &() { return this->Value; }
};
template<class T> T Sticky<T>::LastInitializer;
#include <iostream>
int main(void)
{
Sticky<int> a = 3, b, c = 15, d;
std::cout << "a = " << a << ".n";
std::cout << "b = " << b << ".n";
std::cout << "c = " << c << ".n";
std::cout << "d = " << d << ".n";
b = 4;
std::cout << "b = " << b << ".n";
std::cout << "a = " << a << ".n";
}

输出:

a = 3。 b = 3。 c = 15。 d = 15。 b = 4。 a = 3。

我想你想要这个:

int b=10, a=b;

从技术上讲,您可以使用 C++17 中提供的结构化绑定初始化多个变量,但这显然是一种: 在线编译器

#include <cstddef>
#include <type_traits>
#include <tuple>
#include <utility>
// tuple-like type
template
<
::std::size_t x_count
,   typename x_Value
> class
t_Pack
{
private: x_Value && m_value;
public: constexpr t_Pack(x_Value && value): m_value{::std::move(value)}
{}
public: template
<
::std::size_t x_index
> constexpr auto
get(void) noexcept -> x_Value &&
{
return ::std::move(m_value);
}
};
// specializations to make structured bindings work
namespace std
{
template
<
::std::size_t x_count
,   typename x_Value
> struct
tuple_size<::t_Pack<x_count, x_Value>>
:   public ::std::integral_constant<::std::size_t, x_count> 
{};

template
<
::std::size_t x_index
,   ::std::size_t x_count
,   typename x_Value
> struct
tuple_element<x_index, ::t_Pack<x_count, x_Value>>
{
public: using type = x_Value;
};
}
// helper
template
<
::std::size_t x_count
,   typename x_Value
> constexpr auto
pack(x_Value && value)
{
return t_Pack<x_count, x_Value>{::std::move(value)};
}
auto [a, b, c, d, e] = pack<5>(10);

无法进行初始化。
可以做作业。

int a, b;
a = b = 10;