【问题标题】:Check if template method exists without relying on automated template deduction不依赖自动模板推导检查模板方法是否存在
【发布时间】:2019-04-24 09:40:40
【问题描述】:

如果定义了具有给定签名的模板方法,是否可以编写测试器?

方法的签名如下:

template<typename ReturnType>
ReturnType get(std::string) { return std::declval<ReturnType>(); }

我在这里搜索过,但我发现的都是依赖于自动模板推导的机制 (例如How to test if template function exists at compile time

【问题讨论】:

  • “但我发现的只是依赖于自动模板推导的机制” - 你为什么不直接使用它们?
  • 我会怎么做?自动模板推导在我的示例中不起作用,因为该方法的任何参数都不是必需的类型
  • 澄清一下:您是否需要一种方法来测试template &lt;typename&gt; get(std::string) 是否存在,或者是否可以调用特定的专业化get&lt;T&gt;(std::string)
  • 题外话:您可以在decltype() 中使用std::declval(),而不是在函数体中。
  • @lisyarus 第二个@Scheff 如果定义了我帖子中的签名函数,则助手应该返回true。这是为了更好地阅读错误消息。

标签: c++ templates c++17 sfinae


【解决方案1】:
#include <type_traits>
#include <string>

template <typename T>
constexpr bool test() { return is_invocable<decltype(get<T>), std::string>::value; }

std::is_invocable。但是,如果get&lt;T&gt; 不编译,test&lt;T&gt; 仍然无法编译;请参阅下面的 cmets。

【讨论】:

  • 不知道这个。此处记录的大多数 SFINAE 内容都是 c++17 之前的;谢谢
  • std::is_invocable 的第一个参数是类型,但 get&lt;T&gt; 不是类型:wandbox.org/permlink/ySByqAzEuAnxJsRr
  • @lisyarus 似乎decltype() 修复了建议的解决方案:Fixed Demo on Wandbox
  • @Scheff 它无法区分已定义和未定义的特化,因此只需检查 template &lt;typename&gt; get (std::string) 是否存在,这(在我看来)看起来有些无用:wandbox.org/permlink/FGIlr3lVocP5bFin
  • @lisyarus 我同意。这就是为什么我的评论 defined 的确切含义......(这个例子有点像薛定谔猫:只要你检查模板,它就会被实例化并因此存在。);-)跨度>
猜你喜欢
  • 2011-09-07
  • 2018-05-24
  • 2018-05-01
  • 1970-01-01
  • 2019-11-29
  • 2023-01-24
  • 1970-01-01
  • 2015-10-11
  • 2020-05-30
相关资源
最近更新 更多