以下代码几乎是从 David Abrahams 和 Aleksey Gurtovoy 所著的 C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond 一书的第 9.1.1 节中逐字复制的。
唯一的变化是我希望能够使用常规的 Boost 模板 mpl::identity 更改书中的类型包装器模板。但是,在 Microsoft Visual C++ Express 2010 (SP1) 下,如果我这样做,我会收到一个神秘的编译器警告。
这似乎与类型包装模板有一个名为“type”的内部类型定义有关。将该 typedef 更改为“Type”(或简单地删除该行)将使代码正常工作。有人对这种奇怪的行为有解释吗?
#include <iostream>
#include <typeinfo>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/vector.hpp>
namespace mpl = boost::mpl;
// added a nested typedef named "type" is equivalent to mpl::identity
template <class T>
struct wrap
{
// changing type -> Type or removing this line
// makes the code compile and produce correct output!
typedef T type;
};
struct print_type
{
template <class T>
void operator() (wrap<T>) const
{
std::cout << typeid(T).name() << std::endl;
}
};
class A
{
A() {} // private constructor
};
class B
{
B() {} // private constructor
};
typedef boost::mpl::vector<A,B> AB;
int main()
{
boost::mpl::for_each<AB, wrap<mpl::_> >(
print_type()
);
/* Output:
class A
class B
*/
return 0;
}
输出/I"C:\Program Files\boost\boost_1_47" /I"C:\Program Files\boost" /Zi /nologo /W3 /WX- /O2 /Oi /Oy- /GL /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /Gm- /EHsc /GS /Gy /fp:precise /Zc:wchar_t /Zc:forScope /Fp"Release\mpl.pch" /Fa"Release\" /Fo"Release\" /Fd"Release\vc100.pdb" /Gd /analyze- /errorReport:queue
:
1>------ Build started: Project: mpl, Configuration: Release Win32 ------
1> main.cpp
1>C:\Program Files\boost\boost_1_47\boost/mpl/for_each.hpp(75): error C2784: 'void print_type::operator ()(wrap<T>) const' : could not deduce template argument for 'wrap<T>' from 'arg'
1> ..\..\..\mpl\main.cpp(20) : see declaration of 'print_type::operator ()'
1> C:\Program Files\boost\boost_1_47\boost/mpl/for_each.hpp(101) : see reference to function template instantiation 'void boost::mpl::aux::for_each_impl<false>::execute<first,last,TransformOp,F>(Iterator *,LastIterator *,TransformFunc *,F)' being compiled
1> with
1> [
1> TransformOp=wrap<boost::mpl::_>,
1> F=print_type,
1> Iterator=first,
1> LastIterator=last,
1> TransformFunc=wrap<boost::mpl::_>
1> ]
1> ..\..\..\mpl\main.cpp(42) : see reference to function template instantiation 'void boost::mpl::for_each<AB,wrap<T>,print_type>(F,Sequence *,TransformOp *)' being compiled
1> with
1> [
1> T=boost::mpl::_,
1> F=print_type,
1> Sequence=AB,
1> TransformOp=wrap<boost::mpl::_>
1> ]
========== Build: 0 succeeded, 1 failed, 2 up-to-date, 0 skipped ==========