具有非类型模板参数的方法

Methods with non-type template parameters

本文关键字:参数 方法 类型      更新时间:2023-10-16

我想知道创建非类型模板化类方法的正确语法是什么。我已经试过这个,但显然它不起作用:

class A
{
    enum B
    {
        C = 0,
        D
    };
    template <A::B value = A::C>
    int fun();
};
template<A::B value>
int A::fun<A::B::C>()
{
    return 1;
}
template<A::B value>
int A::fun<A::B::D>()
{
    return fun<B>() + 1;
}

我做错了什么?

问题是您的专用化语法不正确。 它正在尝试对函数进行部分特化,但这在这里甚至没有意义 - 无论如何都是不允许的。

您还尝试在第二个专用化中调用fun<B>(),但B是类型名而不是枚举的值,因此无法解析调用。

试试这个:

// Removed template argument to make a complete specialization instead of partial.
template<>
int A::fun<A::B::C>()
{
    return 1;
}
// Removed template argument to make a complete specialization instead of partial.
template<>
int A::fun<A::B::D>()
{
    // Changed template argument from B (which is a type) to C (which is a value of
    // type B.
    return fun<C>() + 1;
}

您正在尝试部分专用化函数模板,这是不允许的。这是一个可编译的代码片段:

class A
{
    enum B
    {
        C = 0,
        D
    };
    template <A::B value = A::C>
    int fun();
};
template<>
int A::fun<A::B::C>()
{
    return 1;
}
template<>
int A::fun<A::B::D>()
{
    return fun<B::C>() + 1;
}