SFINAE编译器故障 [英] SFINAE compiler troubles
问题描述
下面的代码应该检测 T
是否具有 begin
和 end
方法:
The following code of mine should detect whether T
has begin
and end
methods:
template <typename T>
struct is_container
{
template <typename U, typename U::const_iterator (U::*)() const,
typename U::const_iterator (U::*)() const>
struct sfinae {};
template <typename U> static char test(sfinae<U, &U::begin, &U::end>*);
template <typename U> static long test(...);
enum { value = (1 == sizeof test<T>(0)) };
};
这里是一些测试代码:
#include <iostream>
#include <vector>
#include <list>
#include <set>
#include <map>
int main()
{
std::cout << is_container<std::vector<std::string> >::value << ' ';
std::cout << is_container<std::list<std::string> >::value << ' ';
std::cout << is_container<std::set<std::string> >::value << ' ';
std::cout << is_container<std::map<std::string, std::string> >::value << '\n';
}
在g ++ 4.5.1上,输出为 1 1 1 1
。然而,在Visual Studio 2008上,输出为 1 1 0 0
。我做错了什么,或者这只是一个VS 2008错误?任何人可以测试不同的编译器?谢谢!
On g++ 4.5.1, the output is 1 1 1 1
. On Visual Studio 2008, however, the output is 1 1 0 0
. Did I do something wrong, or is this simply a VS 2008 bug? Can anyone test on a different compiler? Thanks!
推荐答案
Stephan T. Lavavej有 this to say:
Stephan T. Lavavej has this to say:
请注意,技术上禁止使用标准库成员函数的地址。(可以重载它们,使
& foo :: bar
含糊不清,并且可以有其他默认参数,通过static_cast
可以消除歧义。)
Please note that it is technically forbidden to take the address of a Standard Library member function. (They can be overloaded, making
&foo::bar
ambiguous, and they can have additional default arguments, defeating attempts to disambiguate viastatic_cast
.)
所以我想使用更简单的版本,只检查嵌套的 const_iterator
类型。
So I guess I'm going to use the simpler version that only checks for the nested const_iterator
type.
这篇关于SFINAE编译器故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!