CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2006
    Posts
    18

    VC-Compiler (2005) not ANSI-conform (using templates)?

    Hi,

    I've found a strange behaviour of the C++ compiler of VS 2005. Because I'm not sure whether this is a bug (or a non-ANSI-comformity) or whether I've done a mistake, I post it here. The example is directly taken from Stroustrup's C++ bible.

    Imagine two template classes (Vektor<> and Matr<>) for which you want to write an operator*(). Typically this operator-function is designed as being NOT a member of these classes, but a friend. The code is:

    In the header file:
    =============
    Code:
    template<class T> class Matr;
    
    template<class T> class Vektor 
    {
    	T v[4];
    public:
    	friend Vektor operator*<> (const Matr<T>&, const Vektor&);
    };
    
    template<class T> class Matr
    {
    	Vektor<T> v[4];
    public:
    	friend Vektor<T> operator*<> (const Matr&, const Vektor<T>&);
    };
    
    template<class T> Vektor<T> operator*(const Matr<T>& m, const Vektor<T>& v)
    {
    	Vektor<T> vec = v;   // or do anything else...
    	return v;
    }

    In the cpp file:
    ==========
    Code:
    	Vektor<int> vec;
    	Matr<int> mat;
    
    	Vektor<int> res = mat * vec;

    During compilation VC gives the errors:
    syntax error: missing ';' before '<'
    and it points to the lines with the friend declarations.

    When I remove the '<>' behind the operator* in the friend lines, than it compiles but the linker doesn't find the function (which is correct).
    Normally, following the ANSI-syntax, the '<>' should be there. It seems that this is a bug of the VC++ compiler (VS 2005 with SP1).

    Is there something wrong? Has anybody an idea/solution?

    Thanks and bye,
    Physicus.

  2. #2
    Join Date
    Oct 2006
    Posts
    18

    Re: VC-Compiler (2005) not ANSI-conform (using templates)?

    Hi gurus,

    I found the (simple) solution:

    One has to foreward declare the operator-Funktion, before it can be used as a friend in the class declarations. The foreward declaration looks like:

    template<class T> Vektor<T> operator*(const Matr<T>&, const Vektor<T>&);

    Then it works!

    Bye,
    Physicus.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured