Re: Problem with static data members in templated class
On Oct 4, 3:43 pm, Vladimir Jovic <vladasp...@gmail.com> wrote:
Really strange. I copy&paste your code, made this modification, and it
compiled. Are you sure you tried it on the code you posted?
I am not sure if it matters, but I used g++ 4.3.0 and I compiled like thi=
s :
[vladimir@juniper data_create]$ g++ tgf.cpp -Wall -ansi
[vladimir@juniper data_create]$ ./a.out
a
b
a
[vladimir@juniper data_create]$
Thank you for continuing to look at this one for me.
Sorry, I think I did not explain correctly in my original post: the
code as posted compiles, links and runs correctly, but it uses the
copy constructor of class C1 in initialisation. In my final
implementation I need to be able to disable the copy constructor in
C1.
Here is the code, with your modification, but with the initialiser not
using the copy constructor (i.e. I've changed the "#if 0" to a "#if
1", and I've disabled it in C1):
#include <stdio.h>
template <char* T>
struct C1
{
C1() { }
C1(const C1& other) = delete;
char operator()()
{ return *T; }
};
struct C2
{
static char m;
static C1<&m> op;
};
template <typename T>
struct C3
{
static char m;
static C1<&C3<T>::m> op1;
static C1<&C2::m> op2;
};
// Initialise C2::m and C2::op
char C2::m = 'a';
C1<&C2::m> C2::op;
// Initialise C3::m for type int
/** This line fails in Comeau C++ 4.3, but is ok in GCC 4.4 **/
template<> char C3<int>::m = 'b';
// Initialise C3::op2 for type int
template <typename T> C1<&C2::m> C3<T>::op2;
template C1<&C2::m> C3<int>::op2;
// Initialise C2::op1 for type int
#if 1
/** This doesn't compile in GCC 4.4 but does in Comeau C++ 4.3 **/
template <typename T> C1<&C3<T>::m> C3<T>::op1;
template C1<&C3<int>::m> C3<int>::op1;
#elif 0
/** This compiles, but doesn't link **/
template<>
C1<&C3<int>::m> C3<int>::op1;
#else
/** This compiles and links but requires the copy-constructor - bad!
**/
template<>
C1<&C3<int>::m> C3<int>::op1 = C1<&C3<int>::m>();
#endif
int main()
{
printf("%c\n", C2::op());
printf("%c\n", C3<int>::op1());
printf("%c\n", C3<int>::op2());
return 0;
}
When I compile, I get:
$ g++ 1.cpp -Wall -ansi -std=c++0x
1.cpp:42: error: conflicting declaration =91C1<(& C3::m)> C3<T>::op1'
1.cpp:23: error: =91C3<T>::op1' has a previous declaration as =91C1<(&
C3<T>::m)> C3<T>::op1'
1.cpp:42: error: declaration of =91C1<(& C3<T>::m)> C3<T>::op1' outside
of class is not definition
If you are able to get this to compile in GCC 4.3, I will explore
whether this is a bug that's crept into gcc 4.4.
Many, many thanks
Andy