【问题标题】:Call specialized template method basing on enum argument基于枚举参数调用specialize模板方法
【发布时间】:2019-12-29 00:44:06
【问题描述】:

我在处理模板专业化时遇到了一个问题。我想要一个以枚举作为参数的方法,并根据它调用专门的模板化方法。这是演示文稿:

#include <iostream>

enum EnumType
{
    ENUM1,
    ENUM2,
    ENUM3
};

class Test
{
public:
    template <EnumType enumType>
    bool enumFunc(const int i )
    {
        std::cout << i << " default\n";
        return false;
    }

    bool func(const EnumType e);
};

template<>
bool Test::enumFunc<ENUM2>(const int i )
{
    std::cout << i << " ENUM2 \n";
    return true;
}
//... and other specializations

bool Test::func(const EnumType e)
{
    // this one works
    // return enumFunc<ENUM2>(3);

    // but this:
    // error: no matching function for call to 'Test::enumFunc<e>(int)
    return enumFunc<e>(3);
}

int main()
{
    Test a;
    a.enumFunc<ENUM2>(2); // works

    a.func(ENUM2); // doesnt even get there due to previous error

    return 0;
}

【问题讨论】:

  • 请编辑问题以包含您遇到的问题。
  • func 中,您需要一个带有每个枚举值大小写的switch 语句,调用相应的特化。 e 仅在运行时已知,但模板参数必须在编译时已知。
  • @IgorTandetnik 这行得通。我还尝试了 constexpr 开关功能。似乎它也在工作 - 它可以是带有枚举参数的编译时方法的解决方法还是我错了?

标签: c++ templates c++17 template-specialization


【解决方案1】:

如 cmets 中所述,参数 e 的值仅在 运行 时知道,因此您不能使用模板特化(在 编译时间)。以下可能是您的Test::func() 的最简单实现:

bool Test::func(const EnumType e)
{
    switch (e) {
        case ENUM1: return enumFunc<ENUM1>(3);
        case ENUM2: return enumFunc<ENUM2>(3);
        case ENUM3: return enumFunc<ENUM3>(3);
    }
    return false; // Handle error condition(s)
}

【讨论】:

  • 这行得通。我还尝试了 constexpr 开关功能。似乎它的工作 - 它可以是带有枚举参数的编译时方法的解决方法还是我错了?
  • 我不确定您所说的 constexpr switch 是什么意思 - 但如果您的“最终调用的”专业化功能受到限制,它们会受到 许多 限制到“constexpr”返回值。此外,此讨论可能会有所帮助:Switch in constexpr function.
  • @Piodo 您当然可以将constexpr 添加到Test::func 的定义中,但是您只能实际上在其他constexpr 表达式中使用它,如果:(1) enumFunc 的每个特化也被声明为constexpr; (2) 给func 调用的参数也必须const——就像在你的a.func(ENUM2); 语句中一样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-25
  • 1970-01-01
相关资源
最近更新 更多