具有非类型模板参数的方法
Methods with non-type template parameters
我想知道创建非类型模板 class 方法的正确语法是什么。我已经试过了,但显然它不起作用:
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;
}
我做错了什么?
您正在尝试部分特化函数模板,这是不允许的。这是一个可编译的片段:
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;
}
问题是您的专业化语法不正确。它试图对一个函数进行部分特化,但这在这里甚至没有意义——而且无论如何都是不允许的。
您还尝试在第二个特化中调用 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 方法的正确语法是什么。我已经试过了,但显然它不起作用:
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;
}
我做错了什么?
您正在尝试部分特化函数模板,这是不允许的。这是一个可编译的片段:
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;
}
问题是您的专业化语法不正确。它试图对一个函数进行部分特化,但这在这里甚至没有意义——而且无论如何都是不允许的。
您还尝试在第二个特化中调用 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;
}