C ++检测习惯用法无法在Visual Studio 2015 Update 2 CTP中按预期方式工作 [英] The C++ detection idiom is not working as expected in Visual Studio 2015 Update 2 CTP
问题描述
我正在使用建议标准库对C ++检测习惯的支持,并使用 x64的Microsoft C / C ++优化编译器版本19.00.23725 编译了以下代码:
I'm playing with the proposal of standard library support for the C++ detection idiom and compiled the following code with the Microsoft C/C++ Optimizing Compiler Version 19.00.23725 for x64:
#include <iostream>
template<class...>
using void_t = void;
template<class, template<class> class, class = void_t<>>
struct detect : std::false_type { };
template<class T, template<class> class Operation>
struct detect<T, Operation, void_t<Operation<T>>> : std::true_type { };
template<class T>
using bar_t = decltype(std::declval<T>().bar());
template<class T>
using bar_int_t = decltype(std::declval<T>().bar(0));
template<class T>
using bar_string_t = decltype(std::declval<T>().bar(""));
struct foo
{
int bar() { return 0; }
int bar(int) { return 0; }
};
int main()
{
std::cout << detect<foo, bar_t>{} << std::endl;
std::cout << detect<foo, bar_int_t>{} << std::endl;
std::cout << detect<foo, bar_string_t>{} << std::endl;
return 0;
}
预期输出为
1
1
0
但是它是
1
1
1
出了什么问题?我制作了一个实时演示(使用完全相同的代码),其输出与
What is going wrong? I've made a live demo (with exactly the same code) where the output is as expected.
推荐答案
Visual C ++对表达式SFINAE的支持有限,但是,我认为它应该与函数返回类型一起使用。因此,您可以尝试以下实现:
Visual C++ has a limited support for expression SFINAE, however, I think it should work with a function return type. So, instead you can try the below implementation:
#include <type_traits>
template <typename...>
using void_t = void;
template <typename, template <typename> class>
auto detect_impl(char) -> std::false_type;
template <typename T, template <typename> class Operation>
auto detect_impl(int) -> decltype(void_t<Operation<T>>(), std::true_type{});
template <typename T, template <typename> class Operation>
using detect = decltype(detect_impl<T, Operation>(0));
(在 http://webcompiler.cloudapp.net/ )
这篇关于C ++检测习惯用法无法在Visual Studio 2015 Update 2 CTP中按预期方式工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!