C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c如何初始化部分模板特化的静态变量大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我应该如何为部分特化初始化静态变量?
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 = "";

为什么不部分工作?

编辑:我找到了一个基于Partial template specialization for initialization of static data members of template classes解决方

在允许我初始化静态变量之前,我需要重复部分特化的声明:

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 = ""

大佬总结

以上是大佬教程为你收集整理的c如何初始化部分模板特化的静态变量全部内容,希望文章能够帮你解决c如何初始化部分模板特化的静态变量所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。