1

I have the following piece of code where i have genuinely made a syntax mistake:

#include<iostream>
using namespace std;

template<typename Type1,typename Type2>
class Pair{
public:
    Type1 first;
    Type2 second;
    Pair();
    Pair(Pair<Type1,Type2>& obj);
};

template<class Type1,class Type2>
Pair<Type1,Type2>::Pair(){
    first=Type1();
    second=Type2();
}

template<class Type1,class Type2>
Pair<Type1,Type2>::Pair(Pair<Type1,Type2>& obj1){
        cout<<"Inside the copy constructor\n";
        obj1.first=                                //THIS IS THE PROBLEMATIC STMNT
}
int main()
{
/* Code here */
Pair<int,int> com1;
//Pair<complex1,complex2> com2(com1);
}

I dont find any compile/run time errors with this program. However if i uncomment the second line in main which calls the copy constructor then it throws a compiler time error. I know that class instatiates according to the types during runtime, but syntax errors like this for sure are checked in a templatized class during compilation stage. Why no compile time error then? I am using VS2008.

anurag86
  • 1,635
  • 1
  • 16
  • 31

2 Answers2

2

Pair<complex1,complex2> com1; use the default constructor while Pair<complex1,complex2> com2(com1); use the copy constructor.

Since without the second line the copy constructor is never used, it is not compiled; the compiler never generate code for it, therefore it never check if it can compile.

Lorenzo Belli
  • 1,767
  • 4
  • 25
  • 46
  • 7
    It depends on the compiler. For example, gcc returns a compilation error. – Andrey Nasonov Oct 02 '15 at 12:50
  • Seems fair. VS2012 compiles with no warnings. – Lorenzo Belli Oct 02 '15 at 12:56
  • @Lorenzo : it has nothing to do with whether i am calling it or not. I agree that 2nd phase compilation would not be done for copy constructor but copy constructor definition is atleast eligible for 1st phase compilation and basic error like syntax error for sure is caught as a part of compilation process irrespective of i am calling that func(copy constructor) or not – anurag86 Oct 02 '15 at 13:03
1

It's a compiler bug. You can reproduce it in a much simpler way:

template <class T>
void f()
{
   = // should be an error, but is not in MSVC
}

int main()
{
}

This will create a diagnostic message like error: expected primary-expression before '=' token in non-MSVC compilers but compile happily in MSVC.

The apparent reason is that MSVC still has not implemented two-phase lookup as required by the C++ standard. As MSVC developer Stephan T. Lavavej only recently explained in the Visual C++ Team Blog:

VC hasn't implemented three C++98/03 features: two-phase name lookup, dynamic exception specifications, and export. Two-phase name lookup remains unimplemented in 2015, but it's on the compiler team's list of things to do, pending codebase modernization

Community
  • 1
  • 1
Christian Hackl
  • 27,051
  • 3
  • 32
  • 62