gpt4 book ai didi

c++使用带有枚举类和重载转换运算符的模板函数

转载 作者:行者123 更新时间:2023-11-28 01:26:28 25 4
gpt4 key购买 nike

我正在阅读另一篇文章中的示例代码 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 所具有的类型的能力。我尝试了几种不同的方法,但似乎找不到我要找的东西,是否有正确的方法来做到这一点?

最佳答案

您的代码中的问题是您试图使用运行时值而不是编译时值来设置模板类型参数。

Class* a = new A(AllowedType(1)) // The call to new here makes 'type' below a runtime value

b->ability<AllowedTypes::Cat>(); // AllowedTypes::Cat can be supplied at compile time

AllowedTypes type = (AllowedTypes)*a; // this converts correctly!
b->ability<type>(); //does not call correctly

这是您运行的代码 online这指出了确切的问题。下次当你对为什么你的模板类型没有被正确推断/抛出错误感到困惑时,使用 constexpr 来找出原因。

这是一个解释为什么 new 导致格式错误的 constexpr 的答案:C++14: can you call new in a constexpr?

关于c++使用带有枚举类和重载转换运算符的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53550445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com