C + + template static member definition (instantiation)

Source: Internet
Author: User
Tags mutex

Ask questions:

If you have such a template:

class test{public:    static std::string  info;};


What is right (by compiling) for several of the following definitions?

Template <>stringtest<int>::info ("123"); template<typename t>stringTest<t>::info ("123"); template<typename t>stringTest<t>:: Info;template<>stringtest<int>:: info; template<>stringtest<int>:: info (); template<typename t>stringTest<t>::info ();


In order not to affect the analysis and judgment, I put the answer color into a relatively light 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 members for a particular type of template, in our case it simply provides a definition for static member info of the Test<int> class. and call the single-argument constructor initialization.

The second form is similar to the definition of a static member of a normal class, and its effect is implicitly to provide the definition of its static members for all the features of the template, in our case, for the first time using the test<int>,test<float>,test< Char>, ..... The definition of a static member is implicitly provided, and a single-argument constructor is called to initialize.

The third form is consistent with the second form, except that the default constructor is used to initialize it.

Second, explain the three wrong answers.

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

The second form, this is not a declaration of a function.

The third form, the same as the second type.

More content:

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

// A.cpp string Test<t>::info ("4321"); You can use Test<int>:: Info // B.cpp string Test<t>::info ("1234"); You can also use test<int>::info

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

// A.cpp string test<int>::info ("123"); // B.cpp string test<int>::info ("123");

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

// A.cpp string test<int>::info ("123"); // B.cpp string Test<t>::info ("123"); Once you use Test<int


The above method cannot be compiled.

Generally in order to avoid the inability to compile, should try to reduce the use of the following ways to define

Template <typename t> string test<t>::info;

The following special definition is given in the implementation file only when you need it for the first time, and other files can be used as long as the header file is included.

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 applicable or agreed to writing, software * Distributed under the License is distribute D on ' 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#defineAndroid_utils_singleton_h#include<stdint.h>#include<sys/types.h>#include<utils/threads.h>#include<cutils/compiler.h>namespaceAndroid {// ---------------------------------------------------------------------------Template<typename type>classAndroid_api singleton{ Public:    Statictype&getinstance () {Mutex::autolock _l (slock); TYPE* Instance =sinstance; if(Instance = =0) {instance=NewTYPE (); Sinstance=instance; }        return*instance; }    Static BOOLhasinstance () {Mutex::autolock _l (slock); returnSinstance! =0; }    protected:    ~Singleton () {}; Singleton () {};Private:    //disables copying constructors and assignment operator functions, prohibits external and internal classes, and friend calls declare Private,not defineSingleton (Constsingleton&); Singleton&operator= (Constsingleton&); StaticMutex Slock; Statictype*sinstance;};/** Use Android_singleton_static_instance (TYPE) in your implementation file * (eg: <type>.cpp) to create the stat IC instance of singleton<> ' s attributes, * and avoid to has a copy of them in each compilation units singleton<t Ype> * 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 with parameters, otherwise it is declared! *///To use Singleton, you need to include this macro in the implementation file of your custom type to initialize the class template static variable and display the instantiated class template#defineAndroid_singleton_static_instance (TYPE) \Template<> Mutex singleton< TYPE >:: Slock (Mutex::P rivate); \ special Definition Template<> type* singleton< TYPE >::sinstance (0); \ special Definition Templateclasssingleton< TYPE >; \ display instantiation// ---------------------------------------------------------------------------};//namespace Android



C + + template static member definition (instantiation)

Related Article

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.