我有一个元功能:
struct METAFUNCION
{
template<class T>
struct apply
{
typedef T type;
};
};
然后我定义一个助手:
template<class T1, class T2>
struct HELPER
{
};
然后我有第二个元函数,它派生自上面的 METAFUNCTION 并定义了 apply 结构的部分特化:
struct METAFUNCION2 : METAFUNCION
{
template<class T1, class T2>
struct apply<HELPER<T1, T2> > : METAFUNCION::apply<T2>
{
};
};
到目前为止,一切顺利 - 代码在 g++ 4.3.2 下编译。所以我像下面这样使用它:
#include <typeinfo>
#include <string>
#include <cstdlib>
#include <cxxabi.h>
template<typename T>
struct type_info2
{
static std::string name()
{
char *p = abi::__cxa_demangle(typeid(T).name(), 0, 0, 0);
std::string r(p);
free(p);
return(r);
}
};
#include <boost/mpl/apply.hpp>
#include <iostream>
int main()
{
std::cout <<
type_info2<boost::mpl::apply<METAFUNCION, int>::type>::name() <<
std::endl;
std::cout <<
type_info2<boost::mpl::apply<METAFUNCION, HELPER<float, double> >::type>::name() <<
std::endl;
std::cout <<
type_info2<boost::mpl::apply<METAFUNCION2, HELPER<float, double> >::type>::name() <<
std::endl;
return(0);
}
输出:
int
double
double
正如我所料,这让我有点惊讶:
int
HELPER<float, double>
double
现在,我知道上面的代码不能在 Microsoft Visual C++ 2008 下编译(我不记得该消息,但它是我无法在 METAFUNCTION2 结构中专门化 apply 结构的内容)。
所以我的问题是 - 这种 g++ 行为符合标准吗?我有一种强烈的感觉,这里有问题,但我不能 100% 确定。
对于好奇的人 - 当我以这种方式重新定义 METAFUNCTION2 时,我的行为符合我的预期:
struct METAFUNCION2 : METAFUNCION
{
template<class T>
struct apply : METAFUNCION::apply<T>
{
};
template<class T1, class T2>
struct apply<HELPER<T1, T2> > : METAFUNCION::apply<T2>
{
};
};