【发布时间】:2010-12-03 17:00:03
【问题描述】:
我的以下代码应该检测T是否有begin和end方法:
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 错误?任何人都可以在不同的编译器上进行测试吗?谢谢!
【问题讨论】:
-
在 MinGW g++ 4.4.0 上为我工作(得到
1 1 1 1)。不幸的是,我不知道为什么它在 VS2008 上失败,尽管代码看起来是正确的。 -
在 VS2010
1 1 0 0上相同。我有一种预感,它可能正在调试 STL,所以我尝试了/DDEBUG和/DNDEBUG,但没有任何区别。 -
您可以查看 Boost.MPL 提供的
HAS_XXXfacility,了解它们如何解决某些编译器有限的 SFINAE 容量。 -
另一个数据点:Comeau(使用 EDG,通常是一个良好的标准测试)似乎返回
1 1 1 1- 您的程序在他们的在线试用中编译得很好-out comeaucomputing.com/tryitout 将长行注释掉。 -
@Rup:你真的可以在他们的试用网站上运行这个程序吗?
标签: c++ visual-studio-2008 stl containers sfinae