我正在尝试实现我对SO问题here的回答:我的目标是检测模板类T中是否存在void cancel() noexcept方法。下面是我的最小示例:
#include <iostream>
#include <type_traits>
template<class T, class = void>
struct has_cancel : std::false_type {};
template<class T>
struct has_cancel<T,
typename std::void_t<decltype(std::declval<T>().cancel()),
typename std::enable_if_t<noexcept(std::declval<T>().cancel())>
>
> : std::true_type {};
void print_has_cancel(std::true_type) {
std::cout << "cancel found" << std::endl;
}
void print_has_cancel(std::false_type) {
std::cout << "cancel not found" << std::endl;
}
struct A{
};
struct B {
void cancel(){}
};
struct C {
int cancel() noexcept {}
};
struct D{
void cancel() noexcept {}
};
int main(){
print_has_cancel(has_cancel<A>());
print_has_cancel(has_cancel<B>());
print_has_cancel(has_cancel<C>());
print_has_cancel(has_cancel<D>());
return 0;
}来自Visual studio社区2019的输出:
1>------ Build started: Project: cpp_sandbox, Configuration: Debug x64 ------
1>cpp_sandbox.cpp
1>C:\Users\David Haim\source\repos\cpp_sandbox\cpp_sandbox\cpp_sandbox.cpp(10,1): error C2228: left of '.cancel' must have class/struct/union
1>C:\Users\David Haim\source\repos\cpp_sandbox\cpp_sandbox\cpp_sandbox.cpp(10,1): message : type is '_Add_reference<_Ty,void>::_Rvalue'
1>C:\Users\David Haim\source\repos\cpp_sandbox\cpp_sandbox\cpp_sandbox.cpp(10,19): error C2056: illegal expression
1>Done building project "cpp_sandbox.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========经过一些研究,问题出在语法noexcept(std::declval<type>().something()) - MSVC拒绝理解这一行。
1)为什么MSVC会抱怨?bug是在代码中还是在编译器中?
2)我怎么才能让它仍然被编译?
发布于 2020-01-27 14:57:00
MSVC本身的语法没有问题。它似乎只是假设SFINAE在这种情况下不适用,所以将void替换为类型会给出错误。为什么或者在标准中是否有对此的支持,我目前不知道(但我怀疑)。
这可以通过将noexcept条件从声明转移到struct的定义中来轻松解决,这样如果第一个decltype格式错误(即如果.cancel()根本不存在),SFINAE就不会被替换:
template<class T>
struct has_cancel<T,
typename std::void_t<decltype(std::declval<T>().cancel()) >
> : std::bool_constant<noexcept(std::declval<T>().cancel())> {};https://stackoverflow.com/questions/59925948
复制相似问题