C + + template static member definition (instantiation)

Source: Internet
Author: User

Ask a question:

Consider a template:

Template <typename t> class Test{public:    static std::string info;};

There are several ways to define the following. What is right (by compiling)?

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 ();

In order not to affect the analysis of inference, I put the answer color into a lighter color, the following is the answer:

    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


Question Answer:

First, explain the three correct answers.

The first form is called the definition of specificity, and its function is to provide a definition of its static member for a particular special of the template, in our example, it only provides a definition for static member info of the Test<int> class. And the invocation of the single-parameter constructor is initialized.

Another form is similar to the definition of a static member of a normal class, and its function is implicitly to provide the definition of its static member in the compilation unit for the full specificity of the template, in our example, the first use of the test<int>,test<float>,test< Char>, ..... The definition of the static member is implicitly provided, and the single-parameter constructor initialization is called.

The third form is consistent with the other, and the only difference is that it is initialized with the default constructor.

Secondly. Explain the three wrong answers.

The first form of the. A lot of people would think it was right. Feel that it is initialized with the default constructor. However, the compiler makes special processing of the custom definition, which the compiler thinks is a declaration rather than a definition. As for why, you should ask the people who set the standard. I think it may be more difficult to implement this grammar and it is more of a chicken.

Another form, this is not a declaration of a function.

Third form. With the other one.

many other things:

What are the other differences between the two right ways to define them?

A.cpptemplate <typename t> string Test<t>::info ("4321"), able to use Test<int>::info//b.cpptemplate < TypeName t> string Test<t>::info ("1234"), and the ability to use Test<int>::info

These two definitions can coexist in a different compilation unit. The initial value of the Test<int>::info, which depends on the initialization order of the static members, is not a good thing.

A.cpptemplate <> string Test<int>::info ("123");//b.cpptemplate <> string Test<int>::info (" 123 ");

The above method cannot be compiled by the definition of specificity.


The above method cannot be compiled.


In general to avoid the inability to compile, you should try to reduce the use, such as the following methods of definition

Template <typename t> string test<t>::info;
just give the following special definitions in the implementation file for the first time you need to use them, and the other files just include the header file to be used.

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

Application Case:

/* Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License") ; * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by appli Cable law or agreed into writing, software * Distributed under the License is distributed on a "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 () {};p Rivate://Prohibit copy constructors and assignment operator functions, prohibit class external and internal and friend calls 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 having a copy of them in each compilation units Singleton<type > * is used.  * * Note:we Use a version of mutexes ctor that takes a parameter, because * for some unknown reason using the default ctor Doesn ' t emit the variable! A special definition must use a constructor that has parameters, otherwise it is declared. *///To use SINGLETON, you need to include this macro in an implementation file of your own definition type to initialize the class template STATIC variable and display the Instantiation class template # Android_singleton_static_instance (type)  Template<> Mutex singleton< TYPE >::slock (mutex::P rivate);           \ Special Definition template<> type* singleton< TYPE >::sinstance (0); \ special definition template class singleton< TYPE >; \ display instantiation//---------------------------------------------------------------------------}; Namespace Android


Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.

C + + template static member definition (instantiation)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.