提出问题:

如果有这样一个模板:

template <typename T> class Test{
public:
static std::string info;
};

  对于以下若干种定义方式,哪些是对的(通过编译)?

template <> string Test<int>::info("123");
template <typename T> string Test<T>::info("123");
template <typename T> string Test<T>::info;
template <> string Test<int>::info;
template <> string Test<int>::info();
template <typename T> string Test<T>::info();

  为了不影响大家分析判断,我把答案颜色调成比较浅的颜色,下面即是答案:

  1. template <> string Test<int>::info("123");//ok
  2. template <typename T> string Test<T>::info("123");//ok
  3. template <typename T> string Test<T>::info;//ok
  4. template <> string Test<int>::info; //error
  5. template <> string Test<int>::info();//error
  6. template <typename T> string Test<T>::info();//error

问题解答:

首先,说明一下三个正确的答案。

第一种形式称之为特化定义,其作用是为模板某一特化提供其静态成员的定义,在我们例子中,它仅仅为Test<int>类的静态成员info提供定义。并且调用单参数构造函数初始化。

第 二种形式类似于普通类的静态成员的定义方式,其作用是隐式地在该编译单元为模板的所有特化提供其静态成员的定义,在我们例子中,在首次使用 Test<int>,Test<float>,Test<char>...会隐式提供静态成员的定义,并且调用单参 数构造函数初始化。

第三种形式和第二种形式一致,唯一不同就是采用默认构造函数初始化。

其次,说明一下三个错误的答案。

第一种形式,很多人都会认为是对的,认为它采用默认构造函数初始化。但编译器会对特化定义进行特殊处理,编译认为它是一个声明而非定义。至于为什么如此,应该询问一下制定标准的人。我认为可能实现这样的语法可能比较困难并且这个语法也比较鸡肋。

第二种形式,这不成了声明一个函数啦。

第三种形式,同第二种。

更多内容:

两种正确的定义方式还有哪些其他的区别呢?

//a.cpp
template <typename T> string Test<T>::info("4321");
可以使用Test<int>::info
//b.cpp
template <typename T> string Test<T>::info("1234");
也可以使用Test<int>::info

  这两个定义可以在不同的编译单元共存,Test<int>::info的初始值是多少,这取决与静态成员的初始化顺序,所以这不是件好事。

//a.cpp
template <> string Test<int>::info("123");
//b.cpp
template <> string Test<int>::info("123");

  而特化定义,上述方式无法通过编译。

//a.cpp
template <> string Test<int>::info("123"); //b.cpp
template <typename T> string Test<T>::info("123"); 一旦使用Test<int>::info无法通编译

  

上述方式无法通过编译。

一般为了避免无法编译,应当尽量减少使用,如下方式的定义

template <typename T> string Test<T>::info;

只有在你首次需要使用时在实现文件中给出如下特化定义即可,其他文件只要包含头文件就能使用。

template <> string Test<int>::info("123");

应用案例:

/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ #ifndef ANDROID_UTILS_SINGLETON_H
#define ANDROID_UTILS_SINGLETON_H #include <stdint.h>
#include <sys/types.h>
#include <utils/threads.h>
#include <cutils/compiler.h> namespace android {
// --------------------------------------------------------------------------- template <typename TYPE>
class ANDROID_API Singleton
{
public:
static TYPE& getInstance() {
Mutex::Autolock _l(sLock);
TYPE* instance = sInstance;
if (instance == 0) {
instance = new TYPE();
sInstance = instance;
}
return *instance;
} static bool hasInstance() {
Mutex::Autolock _l(sLock);
return sInstance != 0;
} protected:
~Singleton() { };
Singleton() { }; private:
//禁止复制构造函数和赋值运算符函数,禁止类外部和内部以及友元调用 declare private,not define
Singleton(const Singleton&);
Singleton& operator = (const Singleton&);
static Mutex sLock;
static TYPE* sInstance;
}; /*
* use ANDROID_SINGLETON_STATIC_INSTANCE(TYPE) in your implementation file
* (eg: <TYPE>.cpp) to create the static instance of Singleton<>'s attributes,
* and avoid to have a copy of them in each compilation units Singleton<TYPE>
* is used.
*
* NOTE: we use a version of Mutex ctor that takes a parameter, because
* for some unknown reason using the default ctor doesn't emit the variable! 特化定义必须使用有参数的构造函数,否则认为是声明!
*/
//想要使用Singleton,需要在自定义类型的实现文件中包含此宏,用以初始化类模版static变量,并显示实例化类模版
#define ANDROID_SINGLETON_STATIC_INSTANCE(TYPE) \
template<> Mutex Singleton< TYPE >::sLock(Mutex::PRIVATE); \ 特化定义
template<> TYPE* Singleton< TYPE >::sInstance(0); \ 特化定义
template class Singleton< TYPE >; \显示实例化 // ---------------------------------------------------------------------------
}; // namespace android

  

[转]C++ 模板 静态成员 定义(实例化)的更多相关文章

  1. C++模板 静态成员 定义(实例化)

    问一个问题: 考虑一个模板: template <typename T> class Test{ public: static std::string info; }; 对于下面若干种定义 ...

  2. C++ Primer 学习笔记_77_模板与泛型编程 --实例化

    模板与泛型编程 --实例化 引言: 模板是一个蓝图,它本身不是类或函数.编译器使用模板产生指定的类或函数的特定版本号.产生模板的特定类型实例的过程称为实例化. 模板在使用时将进行实例化,类模板在引用实 ...

  3. 读书笔记 effective c++ Item 46 如果想进行类型转换,在模板内部定义非成员函数

    1. 问题的引入——将operator*模板化 Item 24中解释了为什么对于所有参数的隐式类型转换,只有非成员函数是合格的,并且使用了一个为Rational 类创建的operator*函数作为实例 ...

  4. C++模板显式实例化,隐式实例化,特化(具体化,偏特化)辨析

    最近再次看C++ PRIMER PLUS的时候看到这个部分感觉讲得很烂,前后口径不一致,所以写个辨析让自己明白的同时也希望对此不太清楚的朋友能搞懂. 总结一下,C++只有模板显式实例化(explici ...

  5. C++ 模板的编译 以及 类模板内部的实例化

    在C++中.编译器在看到模板的定义的时候.并不马上产生代码,仅仅有在看到用到模板时,比方调用了模板函数 或者 定义了类模板的 对象的时候.编译器才产生特定类型的代码. 一般而言,在调用函数的时候,仅仅 ...

  6. c/c++模板的定义和实现分开的问题及其解决方案

    注意c/c++模板的定义和实现- -                                       定义一个类一般都是在头文件中进行类声明,在cpp文件中实现,但使用模板时应注意目前的C ...

  7. Ext.net Calendar 控件在有模板页的时候,模板页定义了TD的样式造成日历控件的样式丢掉

    Ext.net Calendar 控件在有模板页的时候,模板页定义了TD的样式造成日历控件的样式丢掉 解决方案 在本页面添加下面的样式 <style type="text/css&qu ...

  8. template <typename T>模板类定义

    #include "stdafx.h"#include "iostream"#include <ctime>using namespace std; ...

  9. c++模板使用及实现模板声明定义的分离

    c++模板是编译器构造具体实例类型的模型,使类型参数化,是泛型编程的基础,泛型就是独立于特定类型. 一.模板分为函数模板和类模板两种. 函数模板:template <class 形参名,clas ...

随机推荐

  1. ps 指令

    ps显示系统当前进程信息, ps 存在多个版本,因此 ps options 的种类繁多.这里只列举平时开发过程中常用的命令,如果有错误或者更好的例子.烦请在评论区指出 语法 ps [options] ...

  2. javascript语法糖

    语法糖(Syntactic sugar),也译为糖衣语法 指计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用. 通常来说使用语法糖能够增加程序的可读性,从而减少程序代码 ...

  3. C#基础之结构和类

    大家在平时的工作中对类的使用应该是比较多的,但是在结构使用方面可能稍微少点,这里我就总结一下结构和类的一些异同之处,如有错误之处,还请指正. 结构是值类型,类是引用类型,结构通常用来封装小型相关变量组 ...

  4. entity-framework-core – 实体框架核心RC2表名称复数

    参考地址:https://docs.microsoft.com/zh-cn/ef/core/modeling/relational/tables http://www.voidcn.com/artic ...

  5. 实现CodeFirst自动数据迁移无需手动执行命令

    本主题假设您掌握了实体框架中 Code First 迁移的基本知识. 借助自动迁移功能,您无需对您所做的每一个更改都在程序包管理器控制台中手动Update-Database . 启用迁移 只需执行一次 ...

  6. JS权威指南读书笔记(一)

    第一章 JavaScript概述 1 JS是一门高端的.动态的.弱类型的编程语言,非常适合面向对象和函数式的编程风格.   第二章 词法结构 1 JS程序是用Unicode字符集编写的. 2 JS是区 ...

  7. 原生js实现ajax封装

    一.什么是ajax? 定义:Ajax(Asynchronous Java and XML的缩写)是一种异步请求数据的web开发技术,在不需要重新刷新页面的情况下,Ajax 通过异步请求加载后台数据,并 ...

  8. day24-python之面向对象

    1.面向对象 # name='元昊' # # gender='母' # # type='藏獒' #狗的特征 dog1={ 'name':'元昊', 'gender':'母', 'type':'藏獒' ...

  9. python selenium测试用例断言

    1.if ...else ...判断进行断言 #coding=utf-8 from time import * from selenium import webdriver "): driv ...

  10. WCF Restful Service

    对 Web Services.WCF 和 Restful 的扫盲可参见:https://www.cnblogs.com/scy251147/p/3382436.html 关于之前对 WCF 的学习,可 ...