使用SFINAE来检测void返回类型函数的存在

Using SFINAE to detect existence of a function of void return type

本文关键字:函数 存在 返回类型 void SFINAE 检测 使用      更新时间:2023-10-16

这是我的位置。我试图检测一个类型是否有nlohmann::json,namleyto_json使用的特殊方法。现在,我看到了以下使用SFINAE进行免费功能检查的解决方案:

  • 通过模板检查c++11中是否存在函数(而不是方法(

  • SFINAE:检测类是否具有自由功能

但这些方法似乎至少依赖于函数的返回类型是否为void。在to_json的情况下,签名如下:

void to_json(json& j, const T& p);

返回无效。。。从而使这些方法失败(不管怎样,第二种方法都不起作用,因为为每种类型定义自定义包装器根本不可行(。

我修改了第一种方法,不出所料:

#include <iostream>
#include <type_traits>
#include "json.hpp"
template<class...> struct voider { using type = void; };
template<class... T> using void_t = typename voider<T...>::type;
template<class T, class = void>
struct is_jstreamable : std::false_type{};
template<class T>
struct is_jstreamable<T, void_t<decltype(to_json(std::declval<nlohmann::json &>(),
std::declval<T>()))>> : std::true_type {};
struct Foo;
template<typename T>
typename std::enable_if<is_jstreamable<T>::value,
void>::type
bar(){
std::cout << "It works!" << std::endl;
};
template<typename T>
typename std::enable_if<!is_jstreamable<T>::value,
void>::type
bar(){
std::cout << "It doesn't work!" << std::endl;
}
int main(){
//int does have conversion
bar<int>();
//foo does not have conversion
bar<Foo>();
}

它无法工作,因为它的void类型,控制台返回:

It doesn't work!
It doesn't work!

而不是预期的

It works!
It doesn't work!

我看到了一种确定函数的返回是否为空的方法,但我不确定如何将其解释为我的问题的解决方案

nlohmann::json有多种方法可以将给定类型转换为json。没有为int定义to_json,因此您的类型特征按指定工作。

相反,检测是否可以将类型转换为nlohmann::json对象:

template <typename T>
using is_jstreamable = std::is_convertible<T, nlohmann::json>;

Godbolt 直播