草庐IT

C++11 变量参数对齐

coder 2024-02-12 原文

这是我要实现的界面:

 Statement  select("SELECT * FROM People WHERE ID > ? AND ID < ?");
 select.execute(1462, 1477, [](int ID, std::string const& person, double item1, float item2){
     std::cout << "Got Row:" 
               << ID     << ", " 
               << person << ", " 
               << item1  << ", " 
               << item2  << "\n";
 });

“?”在哪里?选择字符串中的在运行时与变量参数列表 1462、1477 匹配。

这是类定义:

class Statement
{
    public:
        Statement(std::string const&);

        template<class Action, class ...Args>
        void execute(Args... param, Action action);
};

不幸的是,这会产生一个错误:

test.cpp:133:12: error: no matching member function for call to 'execute'
select.execute(1462, 1477, [](int ID, std::string const& person, double item1, float item2){
~~~~~^~~~~~~

test.cpp:86:14: note: candidate template ignored: couldn't infer template argument 'Action'
void execute(Args... param, Action action)
~~~^~~~~~~

1 error generated.

但如果我稍微更改函数定义(如下),它可以正常编译。

class Statement
{
    public:
        Statement(std::string const&);

        template<class Action, class ...Args>
        void execute(Action action, Args... param);
                  // ^^^^^^^ Move action to the front.
};
// Also changed the call by moving the lambda to the first argument.

我知道可变参数列表的语法糖,但我想把可变参数列表放在第一位。有什么技巧可以帮助编译器正确推导 var arg 列表吗?

最佳答案

有点难看,但你可以使用元组:

#include <iostream>
#include <string>
#include <tuple>

template<int... Is>
struct integer_sequence {};
template<int N, int... Is>
struct make_integer_sequence : make_integer_sequence<N-1, N-1, Is...> {};
template<int... Is>
struct make_integer_sequence<0, Is...> : integer_sequence<Is...> {};

class Statement
{
    private:
        std::string foo;

    public:
        Statement(std::string const& p)
            : foo(p)
        {}

        template<class ...Args>
        void execute(Args... param)
        {
            execute_impl(make_integer_sequence<sizeof...(Args)-1>{}, param...);
        }

        template<int... Is, class... Args>
        void execute_impl(integer_sequence<Is...>, Args... param)
        {
            std::get<sizeof...(Args)-1>(std::tie(param...))
                (std::get<Is>(std::tie(param...))..., foo);
        }
};

使用示例:

int main()
{
    Statement s("world");
    s.execute("hello", ", ",
              [](std::string const& p1, std::string const& p2,
                 std::string const& p3)
              { std::cout << p1 << p2 << p3; });
    std::cout << "\nEND\n";
}

这是另一种解决方案,不那么难看但更冗长:

#include <iostream>
#include <string>
#include <tuple>

template<class Tuple, class...>
struct pop_back;

template<class T, class... Ts, class... Us>
struct pop_back<std::tuple<T, Ts...>, Us...>
    : pop_back<std::tuple<Ts...>, Us..., T>
{};

template<class T, class... Us>
struct pop_back<std::tuple<T>, Us...>
{
    using type = std::tuple<Us...>;
};

class Statement
{
    private:
        std::string foo;

    public:
        Statement(std::string const& p)
            : foo(p)
        {}

        template<class ...Args>
        void execute(Args... param)
        {
            helper<typename pop_back<std::tuple<Args...>>::type>
                ::execute(param..., foo);
        }

        template<class T>
        struct helper;

        template<class... Args>
        struct helper< std::tuple<Args...> >
        {
            template<class Action>
            static void execute(Args... param, Action action, std::string foo)
            {
                action(param..., foo);
            }
        };
};

这是一个简短的 is_callable 特性,它允许使用 static_assert 来获得更好的错误消息:

template<class F, class... Args>
struct is_callable
{
    template<class F1>
    static auto test(int)
        -> decltype( std::declval<F1>() (std::declval<Args>()...),
                     std::true_type{} );

    template<class F1>
    static std::false_type test(...);

    constexpr static auto value = decltype(test<F>(0))::value;
};

例如:

template<int... Is, class... Args>
void execute_impl(integer_sequence<Is...>, Args... param)
{
    auto& action = std::get<sizeof...(Args)-1>(std::tie(param...));
    auto param_tuple = std::tie(param...);

    static_assert(is_callable<decltype(action),
                              typename std::tuple_element<Is,
                                              decltype(param_tuple)>::type...,
                              decltype(foo)>::value,
                  "The action is not callable with those argument types.");

    action(std::get<Is>(param_tuple)..., foo);
}

关于C++11 变量参数对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22636151/

有关C++11 变量参数对齐的更多相关文章

  1. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  2. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  3. ruby-on-rails - 如何使用 instance_variable_set 正确设置实例变量? - 2

    我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击

  4. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  5. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  6. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  7. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  8. ruby-on-rails - 如何在我的 Rails 应用程序 View 中打印 ruby​​ 变量的内容? - 2

    我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby​​中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R

  9. ruby-on-rails - 在默认方法参数中使用 .reverse_merge 或 .merge - 2

    两者都可以defsetup(options={})options.reverse_merge:size=>25,:velocity=>10end和defsetup(options={}){:size=>25,:velocity=>10}.merge(options)end在方法的参数中分配默认值。问题是:哪个更好?您更愿意使用哪一个?在性能、代码可读性或其他方面有什么不同吗?编辑:我无意中添加了bang(!)...并不是要询问nobang方法与bang方法之间的区别 最佳答案 我倾向于使用reverse_merge方法:option

  10. ruby - 定义方法参数的条件 - 2

    我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano

随机推荐