【发布时间】:2014-05-22 18:34:50
【问题描述】:
我想根据它所操作的类的枚举成员来专门化模板函数成员的行为。我很确定这是可行的,但我不知道怎么做。这是一个无法编译的失败尝试(为什么?)。事实上,我已经为我的项目找到了一个可行的解决方案(使用继承),但这并不好,我很好奇可以做什么。
#include <iostream>
struct A
{
enum
{
Size = 2
};
};
struct B
{
enum
{
Size = 3
};
};
template <int I>
struct EnumToType
{
static const int e = I;
};
template <typename T, typename U>
struct C {};
template <typename T>
struct D
{
typedef C<T, typename EnumToType<T::Size> > Type;
};
template <typename T>
struct C<T, EnumToType<2> >
{
void operator()()
{
std::cout << "hi !" << std::endl;
}
};
template <typename T>
struct C<T, EnumToType<3> >
{
void operator()()
{
std::cout << "hello !" << std::endl;
}
};
int main()
{
D<A>::Type da;
D<B>::Type db;
da();
db();
return 0;
}
一个有用的link...
【问题讨论】:
-
This question 并回答它可能会有所帮助。