c ++如何初始化部分模板专门化的静态变量 [英] c++ How to initialize static variables of a partial template specialization

查看:218
本文介绍了c ++如何初始化部分模板专门化的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何初始化部分特化的静态变量?

How should I initialize a static variable for a partial 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 = "";

为什么不部分工作?

EDIT:我发现了一个基于的解决方案初始化模板类的静态数据成员的部分模板专门化

I found a solution based on Partial template specialization for initialization of static data members of template classes

我需要重复部分特化的声明,然后才能初始化静态变量:

I need to repeat the declaration for the partial specialization before it allowed me to initialize the static variable:

template <bool B>
struct from<true, B> {
    const static std::string value; 
};

同样,问题是为什么?

推荐答案

如果没有对封装类模板本身进行部分专门化,则不允许成员的部分专门化(无论是函数还是静态数据)。

Partial specialization of members (whether they're functions or static data) are not allowed without partial specialization of enclosing class template itself.

也就是说,你必须专门化类模板。所以以下应该工作:

That is, you have to specialize the class template also. So the following should work:

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

此外,这不会编译(你试过编译这个?):

Also, this will not compile (have you tried compiling this?):

// 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 ++如何初始化部分模板专门化的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆