我应该如何初始化静态变量以实现部分特化?
template <bool A=true, bool B=false>
struct from {
const static std::string value;
};
// no specialization - works
template <bool A, bool B>
const std::string from<A, B>::value = "";
// partial specialization - does not compile -
// Error: template argument list following class template name must list parameters in the order used in template parameter list
// Error: from<A,B>' : too few template arguments
template <bool B>
const std::string from<true, B>::value = "";
// full specialization - works
const std::string from<false, true>::value = "";
为什么部分不起作用?
编辑:我找到了一个基于的解决方案用于初始化模板类的静态数据成员的部分模板特化
在允许我初始化静态变量之前,我需要重复部分特化的声明:
template <bool B>
struct from<true, B> {
const static std::string value;
};
再次,问题是为什么?
如果没有封闭类模板本身的部分专业化,则不允许成员的部分专业化(无论它们是函数还是静态数据)。
也就是说,您还必须专门化类模板。所以以下应该有效:
//partial specialization of class template
template <bool B>
struct from<true, B> {
const static std::string value;
};
//now you can do this!
template <bool B>
const std::string from<true, B>::value = ""
另外,这不会编译(你尝试过编译这个吗?):
// full specialization - works (SORRY, IT WILL NOT WORK!)
const std::string from<false, true>::value = ""; //this should be an error
你必须这样写:
// full specialization
template<> //<---- this is important!
const std::string from<false, true>::value = ""
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)