Can*_*hiu 7 c++ templates template-specialization
我应该如何为部分特化初始化静态变量?
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 = "";
Run Code Online (Sandbox Code Playgroud)
为什么不部分工作?
编辑:我找到了一个基于部分模板专业化的解决方案,用于初始化模板类的静态数据成员
在允许我初始化静态变量之前,我需要重复部分特化的声明:
template <bool B>
struct from<true, B> {
const static std::string value;
};
Run Code Online (Sandbox Code Playgroud)
同样,问题是为什么?
如果没有封闭类模板本身的部分专业化,则不允许成员的部分专业化(无论它们是函数还是静态数据)。
也就是说,您还必须专门化类模板。所以以下应该有效:
//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 = ""
Run Code Online (Sandbox Code Playgroud)
另外,这不会编译(你尝试过编译这个吗?):
// full specialization - works (SORRY, IT WILL NOT WORK!)
const std::string from<false, true>::value = ""; //this should be an error
Run Code Online (Sandbox Code Playgroud)
你必须这样写:
// full specialization
template<> //<---- this is important!
const std::string from<false, true>::value = ""
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3301 次 |
最近记录: |