PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

[FIXED] How to initialize static members of two various types of template class

 July 08, 2022     c++, class, initialization, static, templates     No comments   

Issue

I want to assign two different values to A<int> and A<char>,then each kind of instantialized classes have their own static member 'a',but the program compile failed.

Here's the code.

#include <iostream>
using namespace std;
template<class T>
class A {
private:
    static int a;
public:
    friend ostream& operator<<<T>(ostream& os, A<T>& p); 
};
template<class T>
ostream& operator<<(ostream& os, A<T>& p){
    cout << p.a;
    return os;
}
template<class T>int A<T>::a = 5;
template<class T>char A<T>::a = 50;//error:the declaration is not compatible with the previous "int A<T>::A"declaration
int main()
{
    A<int> v1, v2, v3;
    A<char>v11, v22, v33;
    cout << v1<<" "<<v2<<" "<<v3<<endl;

}

So what should I do?


Solution

You need to do an explicit specialization which you do by writing an empty template declaration and replacing T in A<T> with the type you want.

template<> int A<int>::a = 5;
template<> int A<char>::a = 50;


Answered By - David G
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing