可以使用支撑的数字列表作为传递给可变函数(或构造函数)的参数吗?

时间:2018-04-08 14:17:49

标签: c++

可以使用支持的数字列表{0x00,0x01,0x02}作为传递给可变函数(或构造函数)的参数吗?

在下面的代码中,我可以成功编译并调用它:

BlobClass blob('A', "xyz", 'B', sss, 'C');

但以下甚至没有编译:

BlobClass blob('A', {0x00, 0x01, 0x02},  'B', sss , 'C');

有没有办法让它适用于以下类?:

class BlobClass
{
protected:
    unsigned char data[512];

    void memcpy_var(unsigned char*) // variadic memcpy terminator
    {
    }

    template <typename... REMAINING>
    void memcpy_var(unsigned char* Dest, const std::string& Peeled, const REMAINING&... RemainingArgs){ // variadic memcpy for std strings
        size_t TheSize = Peeled.size();
        std::memcpy(Dest, Peeled.c_str(), TheSize);
        memcpy_var(Dest + TheSize, RemainingArgs...);
    }

    template <typename... REMAINING>
    void memcpy_var(unsigned char* Dest, const char* Peeled, const REMAINING&... RemainingArgs){    // variadic memcpy for C strings
        while (*Peeled != 0)
            *Dest++ = *Peeled++;

        memcpy_var(Dest, RemainingArgs...);
    }

    template <typename... REMAINING>
    void memcpy_var(unsigned char* Dest, const char& Peeled, const REMAINING&... RemainingArgs){    /// variadic memcpy for single Chars
        *Dest = Peeled;
        memcpy_var(Dest + 1, RemainingArgs...);
    }

public:
    template<typename... ARGS>
    BlobClass(ARGS&&... args) {         //Variadic constructor
        memcpy_var(&data[0], args...);
    }

    BlobClass();
}


int main()
{   
    std::string sss("str");

    BlobClass blob('A', "xyz", 'B', sss, 'C');              //This works fine
    BlobClass blob('A', {0x00, 0x01, 0x02},  'B', sss , 'C');       //This does not compile with the error: "no overloaded function takes 5 arguments"
}

我尝试添加以下功能,但不起作用:

template <typename... REMAINING>
void memcpy_var(unsigned char* Dest, const std::initializer_list<int>& Peeled, const REMAINING&... RemainingArgs){  // variadic memcpy for an entire initialier list
    size_t TheSize = sizeof Peeled;
    std::memcpy(Dest, &Peeled, TheSize);
    memcpy_var(Dest + TheSize, RemainingArgs...);
}

P.S。 我知道这个类有不安全的代码,因为memcpy_var()可以溢出数据[512]缓冲区。为简洁起见,我清理了边界检查代码。

1 个答案:

答案 0 :(得分:1)

当然,但最好的方法是将for s in evidences_images: if s.image_title == form.cleaned_data.get("image_title"): context = { 'evidence': evidence, 'form': form, 'error_message': 'You already added that image', } return render(request, 'fir/create_image.html', context) image = form.save(commit=False) image.evidence = evidence image.image_file = request.FILES['image_file'] file_type = image.image_file.url.split('.')[-1] file_type = file_type.lower() 的功能专门化,因为我认为你想为这些做些不同的事情。

可能的实施可能是以下方向

std::initializer_list<T>

行动中:https://godbolt.org/g/Dx3nsm