我正在阅读另一篇文章Specializations only for C++ template function with enum non-type template parameter上的示例代码
我试图更进一步,通过使用重载的转换运算符来使用对象,就好像它是调用模板函数的枚举成员一样。
//in my .h
enum class AllowedTypes { Cat, Dog };
class A {
AllowedTypes animal;
public:
//constructor
A(AllowedTypes t): animal(t) {};
explicit operator AllowedTypes*() const { return (AllowedTypes*) animal; }
operator AllowedTypes() const { return animal; }
template <AllowedTypes type>
void ability() const;
}
//second class
struct B{
//tempalte function
template <AllowedTypes type>
void ability() const;
}
//in my cpp
template<>
void B::ability<AllowedTypes::Dog>() const
{
std::cout << "Dog ability." << std::endl;
}
template<>
void B::ability<AllowedTypes::Cat>() const
{
std::cout << "Cat ability." << std::endl;
}
//in my main
Class* a = new A(AllowedType(1))
Class* b = new B();
//this calls work!
b->ability<AllowedTypes::Cat>();
//trying to get the type and calling ability via conversion doesn't
AllowedTypes type = (AllowedTypes)*a; // this converts correctly!
b->ability<type>(); //does not call correctly
最后一行不起作用,我试图将转换后的对象放入模板中并调用特定于 A 类型的能力。我尝试了一些不同的东西,但似乎找不到我要找的东西,有没有合适的方法来做到这一点?