相关疑难解决方法(0)

将const_cast元素移出std :: initializer_list会有任何风险吗?

这个问题建立在这个@ FredOverflow的问题上.

澄清:initializer_list需要方法,因为VC++ 2012有一个错误,阻止了命名空间参数的转发扩展._MSC_VER <= 1700有错误.

我编写了一个可变参数模板函数,它可以折叠类型化容器中的任意数量的参数.我使用类型的构造函数将可变参数转换为可使用的值.例如_variant_t:)

MySql在一次打击MySqlVariant中将参数推送到预准备语句时,我需要这个用于我的C++库,而我将输入数据转换为MYSQL_BINDs.因为我可以使用BLOBs,所以当我可以move&&使用大容器时,我希望尽可能避免复制构造.

我做了一个简单的测试,发现了initialize_list确实copy-construct为存储的元素,当它超出范围破坏它们.完美...然后我试图将数据移出,initializer_list并且令我惊讶的是,它并lvalues没有rvalues像我预期的那样使用std::move.

有趣的是,就在Going Native 2013之后发生了明显的警告我,移动不动,前进不会前进 ...... 就像水,我的朋友 - 留在思考的深层.

但这并没有阻止我:)我决定const_castinitializer_list价值观,仍然将它们移出去.需要强制执行驱逐令.这是我的实施:

template <typename Output_t, typename ...Input_t>
inline Output_t& Compact(Output_t& aOutput, Input_t&& ...aInput){
    // should I do this? makes sense...
    if(!sizeof...(aInput)){
        return aOutput; …
Run Code Online (Sandbox Code Playgroud)

c++ c++11

12
推荐指数
1
解决办法
561
查看次数

可变参数扩展可以用作逗号运算符调用链吗?

我在看“如何正确使用可变参数模板的引用”,并想知道逗号扩展可以走多远。

这是答案的一个变体:

inline void inc() { }

template<typename T,typename ...Args>
inline void inc(T& t, Args& ...args) { ++t; inc(args...); }
Run Code Online (Sandbox Code Playgroud)

由于可变参数被扩展到一逗号-分隔它们的元素的列表,是那些逗号语义上等同于模板/功能参数的分离器,或者他们插入词法,使得它们适用于任何(-预处理后)的使用,包括逗号操作符?

这适用于我的 GCC-4.6:

// Use the same zero-argument "inc"

template<typename T,typename ...Args>
inline void inc(T& t, Args& ...args) { ++t, inc(args...); }
Run Code Online (Sandbox Code Playgroud)

但是当我尝试时:

// Use the same zero-argument "inc"

template<typename T,typename ...Args>
inline void inc(T& t, Args& ...args) { ++t, ++args...; }
Run Code Online (Sandbox Code Playgroud)

我不断收到解析错误,期待“;” 在“...”之前,并且“args”不会扩展其包。为什么不起作用?是因为如果“args”为空,我们会得到一个无效的标点符号?合法吗,我的编译器不够好?

(我试过在括号中围绕“args”,和/或使用后增量;都没有奏效。)

c++ variadic comma c++11

5
推荐指数
1
解决办法
1223
查看次数

如何使用可变参数模板打印出函数的参数?

这个例子使用了一个通用的可变参数模板和函数。我想打印出传递给的参数f

#include <iostream>

template <typename T>
void print(T t) 
{
    std::cout << t << std::endl;
}

template <typename...T>
void f(T &&...args) 
{
    print(args...);
    f(args...);
}

int main() 
{
    f(2, 1, 4, 3, 5);
}
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

Compilation finished with errors:<br>
source.cpp: In instantiation of '`void f(T ...)` [with `T = {int, int, int, int, int}`]':<br>
source.cpp:16:20: required from here <br>
source.cpp:10:4: error: no matching function for call to '`print(int&, int&, int&, int&, int&)`'<br>
source.cpp:10:4: note: candidate is:<br>
source.cpp:4:6: note: …
Run Code Online (Sandbox Code Playgroud)

c++ templates generic-programming function-templates variadic-templates

2
推荐指数
1
解决办法
3367
查看次数