草庐IT

c++ - 获取函数的地址并在编译时丢弃它 : is this valid C++?

coder 2024-02-23 原文

我一直在寻找一种方法来将模板类型参数限制为那些实现给定签名功能的参数。我似乎已经找到了一个非常优雅的解决方案,它允许 self 记录代码和相当干净的、类似于概念的错误消息。唯一的问题是我不确定那是有效的 C++ 还是恰好在 clang 和 gcc 中工作的东西。

代码如下:

#include <type_traits>
using std::enable_if;

// let's say we want something with a "regular" operator+

class Thing
{
public:
    Thing operator+(const Thing&){return Thing();} //the kind of operator we want
};

class OtherThing
{
public:
    OtherThing operator+(int){return OtherThing();} // the kind of operator we don't want
};

class YetAnotherThing
{
    // no operator whatsoever
};

// The questionable line. I'm taking the address of the function and 
// immediately discarding it using the comma operator.
#define HAS_FUNCTION(type, ret, name, args...) (static_cast<ret (type::*)(args)>(&type::name), 1)

#define T_HAS_OPERATOR_PLUS HAS_FUNCTION(T, T, operator+, const T&)

template <typename T>
typename enable_if<T_HAS_OPERATOR_PLUS>::type foo(T)
{
    T t1, t2;
    t1 + t2;
}

#undef T_HAS_OPERATOR_PLUS

int main()
{
    Thing t;
    OtherThing ot;
    YetAnotherThing yat;
    foo(t);
    foo(ot);
    foo(yat);
}

当使用 clang 构建时,它会产生以下输出:

main.cpp:43:2: error: no matching function for call to 'foo'
        foo(ot);
        ^~~
main.cpp:29:47: note: candidate template ignored: substitution failure [with T = OtherThing]: static_cast from 'OtherThing (OtherThing::*)(int)' to 'OtherThing (OtherThing::*)(const OtherThing &)' is not allowed
typename enable_if<T_HAS_OPERATOR_PLUS>::type foo(T)
                   ~~~~~~~~~~~~~~~~~~~        ^
main.cpp:44:2: error: no matching function for call to 'foo'
        foo(yat);
        ^~~
main.cpp:29:47: note: candidate template ignored: substitution failure [with T = YetAnotherThing]: no member named 'operator+' in 'YetAnotherThing'
typename enable_if<T_HAS_OPERATOR_PLUS>::type foo(T)
                   ~~~~~~~~~~~~~~~~~~~        ^
2 errors generated.

...与通常的奥术暴风雪相比,这看起来相当不错。

所以,我的问题是:它在标准 C++14 中有效吗?毕竟我在编译时获取地址,这似乎是标准不允许的事情。

此外,由于我只是黑魔法的学徒,也许有更直接的方法来完成此任务?

无论哪种方式,我们都欢迎任何意见。提前致谢。

最佳答案

首先,boost TypeTraits 有一个实现,您可以使用它而无需自己滚动 - 参见 here .其次,您通常只希望在存在多个潜在重载并且希望从候选集中删除一些重载时使用 enable_if。如果您只是想强制 T 满足某个概念,那么使用 static_assert 会更简洁。例如:

template <typename T>
auto foo(T)
{
    static_assert(boost::has_plus<T, T>::value, "T must support operator+");
    // Impl...
}

关于c++ - 获取函数的地址并在编译时丢弃它 : is this valid C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33092169/

有关c++ - 获取函数的地址并在编译时丢弃它 : is this valid C++?的更多相关文章

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

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

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

  3. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  4. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  5. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  6. ruby - 从 Ruby 中的主机名获取 IP 地址 - 2

    我有一个存储主机名的Ruby数组server_names。如果我打印出来,它看起来像这样:["hostname.abc.com","hostname2.abc.com","hostname3.abc.com"]相当标准。我想要做的是获取这些服务器的IP(可能将它们存储在另一个变量中)。看起来IPSocket类可以做到这一点,但我不确定如何使用IPSocket类遍历它。如果它只是尝试像这样打印出IP:server_names.eachdo|name|IPSocket::getaddress(name)pnameend它提示我没有提供服务器名称。这是语法问题还是我没有正确使用类?输出:ge

  7. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

  8. ruby-on-rails - 获取 inf-ruby 以使用 ruby​​ 版本管理器 (rvm) - 2

    我安装了ruby​​版本管理器,并将RVM安装的ruby​​实现设置为默认值,这样'哪个ruby'显示'~/.rvm/ruby-1.8.6-p383/bin/ruby'但是当我在emacs中打开inf-ruby缓冲区时,它使用安装在/usr/bin中的ruby​​。有没有办法让emacs像shell一样尊重ruby​​的路径?谢谢! 最佳答案 我创建了一个emacs扩展来将rvm集成到emacs中。如果您有兴趣,可以在这里获取:http://github.com/senny/rvm.el

  9. Ruby 从大范围中获取第 n 个项目 - 2

    假设我有这个范围:("aaaaa".."zzzzz")如何在不事先/每次生成整个项目的情况下从范围中获取第N个项目? 最佳答案 一种快速简便的方法:("aaaaa".."zzzzz").first(42).last#==>"aaabp"如果出于某种原因你不得不一遍又一遍地这样做,或者如果你需要避免为前N个元素构建中间数组,你可以这样写:moduleEnumerabledefskip(n)returnto_enum:skip,nunlessblock_given?each_with_indexdo|item,index|yieldit

  10. ruby - Net::HTTP 获取源代码和状态 - 2

    我目前正在使用以下方法获取页面的源代码:Net::HTTP.get(URI.parse(page.url))我还想获取HTTP状态,而无需发出第二个请求。有没有办法用另一种方法做到这一点?我一直在查看文档,但似乎找不到我要找的东西。 最佳答案 在我看来,除非您需要一些真正的低级访问或控制,否则最好使用Ruby的内置Open::URI模块:require'open-uri'io=open('http://www.example.org/')#=>#body=io.read[0,50]#=>"["200","OK"]io.base_ur

随机推荐