【问题标题】:Methods with non-type template parameters具有非类型模板参数的方法
【发布时间】:2017-05-10 13:54:24
【问题描述】:
我想知道创建非类型模板类方法的正确语法是什么。我已经尝试过了,但显然它不起作用:
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;
}
我做错了什么?
【问题讨论】:
标签:
c++
templates
metaprogramming
non-type
【解决方案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;
}
【解决方案2】:
您正在尝试对函数模板进行部分特化,这是不允许的。这是一个可编译的sn-p:
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;
}