【问题标题】:template specialization and static members initialization模板特化和静态成员初始化
【发布时间】:2019-01-19 15:17:02
【问题描述】:

假设有一个模板类:

template<typename T>
class Storage
{
public:
    static std::map<T, std::vector<std::string> > things;
};

现在我想将它专门用于int 类型并初始化things

目前我发现的不抛出编译错误的方法是这样的:

template<>
std::map<int, std::vector<std::string> > Storage<int>::things = {
    { 1, {"FOO", "foo"} },
    { 2, {"BAR", "bar"} },
    { 3, {"ZAR", "zar"} }
};

但是我们怎么可以同时特化类和初始化静态成员呢?

【问题讨论】:

    标签: c++ c++11 templates specialization


    【解决方案1】:

    代码:

    template<>
    std::map<int, std::vector<std::string> > Storage<int>::things = {
        { 1, {"FOO", "foo"} },
        { 2, {"BAR", "bar"} },
        { 3, {"ZAR", "zar"} }
    };
    

    不是类模板Storage的特化,而是a static data member of a class template的特化。

    模板类的成员可以特化(只要没有非静态数据成员)。也就是说,可以将整个模板类特化为一个整体,如下所示:

    template<class T>
    struct A{
       struct B{
          using type = T;
          };
        void g();
        };
    
     template<>
     struct A<void>{}; //specialize the entire class.
    

    或者只特化类模板的成员:

    //Specialization of B for A<int>
    template<>
    struct A<int>::B{
       static int f();
       };
    

    上述成员特化等价于模板类特化:

    template<>
    struct A<int>{
       struct B{ //come from the member specialization definition
         static int f();
         };
       void g(); //come from unspecialized A definition.
       };
    

    因此,如果您尝试编译,您可能会观察到这一点:

    A<char>::B::type x = `a`; 
    A<double>::B::type y = `b`; 
    
    A<int>::B::type err; //compilation error
    int z = A<int>::B::f(); //ok.
    
    A<void>::B o; //compilation error
    auto w = A<void>::f(); //compilation error
    

    【讨论】:

    • "模板类的成员可以特化(只要没有非静态数据成员)。" 在代码示例class存储中不包含任何非静态数据成员,那么如何模板类可以有专门的成员吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多