使用decltype
和std::enable_if_t
进行简单有效的SFINAE选择非常常见(至少在我的代码中)。如下所示:
template <typename A1, typename A2, typename... Auts>
inline
auto
infiltration(const A1& a1, const A2& a2, const Auts&... as)
-> decltype(std::enable_if_t<sizeof...(Auts) != 0>{},
infiltration(infiltration(a1, a2), as...))
{
return infiltration(infiltration(a1, a2), as...);
}
但是,由于某种原因,void{}
无效(至少对于Clang和GCC而言),所以我不能这样写:我必须使用()
来实例化我的std::enable_if_t
:
$ cat foo.cc
auto foo() -> decltype(void()) {}
auto bar() -> decltype(void{}) {}
int main()
{
foo();
bar();
}
$ clang++-mp-3.6 -std=c++14 foo.cc
foo.cc:2:32: error: illegal initializer type 'void'
auto bar() -> decltype(void{}) {}
^
1 error generated.
$ clang++-mp-3.7 -std=c++14 foo.cc
foo.cc:2:32: error: illegal initializer type 'void'
auto bar() -> decltype(void{}) {}
^
1 error generated.
$ g++-mp-5 -std=c++14 foo.cc
foo.cc:2:33: error: compound literal of non-object type 'void'
auto bar() -> decltype(void{}) {}
^
foo.cc:2:33: error: compound literal of non-object type 'void'
foo.cc: In function 'int main()':
foo.cc:7:11: error: 'bar' was not declared in this scope
bar();
^
为什么?