c++ - 如何让列表可以隐式转换为我的类对象?

标签 c++ c++11 list-initialization

例如,我有一个类 Point 并且有一个函数

void foo(Point pt);

称之为

foo({1, 2, 3});

最佳答案

#include <initializer_list>
#include <cassert>

struct bar
{
    void foo(const std::initializer_list<int>& bits)
    {
        assert(bits.size() == 3);
        auto i = bits.begin();
        x = *i++;
        y = *i++;
        z = *i++;
    }

    int x, y, z;
};

int main()
{
    bar b;
    b.foo({0, 1, 2});
}

关于c++ - 如何让列表可以隐式转换为我的类对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34052539/

相关文章:

c++ - Boost Asio C++ HTTPS 请求未命中服务器。没有错误

c++ - 使用 sleep() 以一秒为间隔打印数组元素

c++11 - 为什么在g++中-ansi和-std = c++ 11会冲突?

c++ - 当参数是引用时,可变参数模板构造函数选择失败

c++ - boost::condition_variable.timed_wait 立即返回

c++ - 为什么存储整数的内存块的值会反复变化?

c++ - std::add_pointer,try_add_pointer 在可能的实现中有什么用?

c++ - 为什么 ={} 初始化不适用于元组?

c++ - GCC 不支持 new 表达式中的大括号省略

c++ - 当参数是初始化列表且参数是引用时的重载解析