jjzjj

c++ - enable_if 添加具有默认参数的函数参数?

coder 2024-01-31 原文

我无法理解呈现的第二种情况 here .它说:

•Scenario 2: Adding a function parameter that has a default argument:

template <your_stuff> your_return_type_if_present
yourfunction(args, enable_if_t<your condition, FOO> = BAR) {
    // ...
}

Scenario 2 leaves the parameter unnamed. You could say ::type Dummy = BAR, but the name Dummy is irrelevant, and giving it a name is likely to trigger an unreferenced parameter warning. You have to choose a FOO function parameter type and BAR default argument. You could say int and 0, but then users of your code could accidentally pass to the function an extra integer that would be ignored. Instead, we recommend that you use void ** and either 0 or nullptr because almost nothing is convertible to void **:

template <your_stuff> your_return_type_if_present 
yourfunction(args, typename enable_if<your_condition, void **>::type=nullptr) {
 // ...
}

如果场景 2 未命名参数,那么它可以用在什么地方? 有没有办法让这样的代码与 enable_if 一起工作?

enum otype {oadd,omull};
template<otype o>
int add(int num1, std::enable_if<o == oadd, int>::type int= num2)
{
    if (o == omull) return num1 * num1;
    if (o == oadd ) return num1 + num2;
 }

最佳答案

Microsoft 的文档 there 那里清澈如泥。使用 this相反。

提供一个带有未命名默认参数的函数模板:

typename enable_if<your_condition, void **>::type = nullptr

(正如 MS 抄写员所建议的),在您希望的情况下很有用 - 并且仅在情况下 - 编写具有不同行为的函数模板的多个重载 由一个或多个模板参数控制。然后,通过 将 your_condition 替换为表达适当条件的条件 对模板参数的要求,您可以使用 SFINAE 选择要为其实例化的特定重载的原则 给定模板参数。

SFINAE 参数 - 让我们这样调用它 - 是 未被实例化函数使用;它的存在仅仅是为了在函数模板中激发 SFINAE 过载决议。因此它可以是无名的,因此它必须是默认的: 它不能强制你提供额外的、无用的论据 调用函数模板。

例如:

#include <type_traits>
#include <iostream>

template <typename T>
T foo(T && t, 
    typename std::enable_if<std::is_same<T,int>::value, void **>::type = nullptr)
{
    std::cout << "Doubling " << t << " gives " << (t + t) << std::endl;
    return t + t; 
}

template <typename T>
T foo(T && t, 
    typename std::enable_if<!std::is_same<T,int>::value, void **>::type = nullptr)
{
    std::cout << "Squaring " << t << " gives " << (t * t) << std::endl;
    return t * t; 
}

using namespace std;

int main()
{
    cout << foo(2) << endl;
    cout << foo(3.3) << endl;
    return 0;
}

输出是:

Doubling 2 gives 4
4
Squaring 3.3 gives 10.89
10.89

在函数模板 foo 的这两个重载中,第一个将它加倍 类型 T 参数和第二个平方它的参数,和一个 SFINAE 参数用于确定将实例化倍增重载 如果 Tint,否则将选择平方重载。

Tint时,条件:

!std::is_same<T,int>::value

控制平方重载的 SFINAE 参数为假。最后 类型说明符:

typename std::enable_if<!std::is_same<T,int>::value, void **>::type = nullptr

编译失败。这是模板解析中的替换失败。代入 平方重载中 Tint 不可行。所以平方重载是 从运行中消除,只剩下加倍重载实例化 函数调用。

T 是(比方说)double 而不是 int 时,则恰恰相反 并且只有平方重载在模板解析中幸存下来。调用 foo(2) 你得到加倍。调用 foo(3.3) 即可得到平方。

此处 MS 的样本 SFINAE 参数不必要地冗长。

template< bool B, class T = void >
struct enable_if;

根据 C++11 标准及更高版本,默认 Tvoid。所以像:

typename std::enable_if<some_condition, void **>::type = nullptr

也可以缩写为:

typename std::enable_if<some_condition>::type * = nullptr

从 C++14 开始,标准有:

template< bool B, class T = void >
using enable_if_t = typename enable_if<B,T>::type

所以同样的SFINAE参数可以进一步缩短为:

std::enable_if_t<some_condition> * = nullptr

将 SFINAE 函数模板参数应用于您在 发布,你会这样写:

enum ops {
    add,
    multiply
};

template<ops Op>
int op(int const & lhs, int const & rhs, 
        std::enable_if_t<Op == add> * = nullptr)
{
    return lhs + rhs;
}

template<ops Op>
int op(int const & lhs, int const & rhs, 
        std::enable_if_t<Op == multiply> * = nullptr)
{
    return lhs * rhs;
}

...

auto i = op<add>(2,3);
auto j = op<multiply>(2,3);

...
// C++14

关于c++ - enable_if 添加具有默认参数的函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29040059/

有关c++ - enable_if 添加具有默认参数的函数参数?的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  3. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  4. 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您的程序将作为解释器的子进程执行。除

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

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

  6. ruby - 默认情况下使选项为 false - 2

    这是在Ruby中设置默认值的常用方法:classQuietByDefaultdefinitialize(opts={})@verbose=opts[:verbose]endend这是一个容易落入的陷阱:classVerboseNoMatterWhatdefinitialize(opts={})@verbose=opts[:verbose]||trueendend正确的做法是:classVerboseByDefaultdefinitialize(opts={})@verbose=opts.include?(:verbose)?opts[:verbose]:trueendend编写Verb

  7. 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

  8. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  9. 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"

  10. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

随机推荐