[英]Using SFINAE to detect existence of a function of void return type
Here's my situaition. 这是我的情况。 I'm trying to detect if a type has special methods utilized by nlohmann::json , namley
to_json
. 我正在尝试检测类型是否具有nlohmann :: json和namley
to_json
使用的特殊方法。 Now I've seen the following solutions for free function checking with SFINAE: 现在,我已经看到了以下使用SFINAE进行免费功能检查的解决方案:
Checking whether a function (not a method) exists in c++11 via templates 通过模板检查c ++ 11中是否存在函数(不是方法)
SFINAE: detect if class has free function SFINAE:检测类是否具有自由功能
but these methods at least appear to rely on the return type of a function being void or not. 但是这些方法至少看起来依赖于函数的返回类型是否为空。 in the case of
to_json
the signature is as follows: 对于
to_json
,签名如下:
void to_json(json& j, const T& p);
which returns void... thus makes these methods fail (the second doesn't really work regardless since defining a custom wrapper for each type simply is not feasible). 返回void ...从而使这些方法失败(第二种方法实际上不起作用,因为为每种类型定义自定义包装程序根本不可行)。
I modified the first method, and as expected: 我修改了第一种方法,并且符合预期:
#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>();
}
it fails to work because its void type, the console returning: 它无法工作,因为其无效类型,控制台返回:
It doesn't work!
It doesn't work!
instead of the expected 而不是预期的
It works!
It doesn't work!
I saw a method for determining if the return of a function is void but I'm unsure of how to incorprate that as a solution of my problem 我看到了一种确定函数返回是否为空的方法,但不确定如何将其合并为问题的解决方案
nlohmann::json has multiple ways to convert a given type to json. nlohmann :: json有多种将给定类型转换为json的方法。 There is no
to_json
defined for int
, so your type trait is working as specified. 没有为
int
定义to_json
,因此您的类型特征正在按指定方式工作。
Instead, detect if you can convert the type to a nlohmann::json
object: 相反,检测是否可以将类型转换为
nlohmann::json
对象:
template <typename T>
using is_jstreamable = std::is_convertible<T, nlohmann::json>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.