Re: 14/8 says my code is right, compiler says it's wrong
Matthias Hofmann ha scritto:
// ---------- begin file "item.h" ----------
template <class T> struct item_traits;
template <class T> class Item
{
public:
typedef item_traits< Item<T> > traits_type;
int foo() { return traits_type::foo(); } // Error C2027
};
// ---------- end file "item.h" ----------
// ---------- begin file "item.cpp"----------
#include "item.h"
template <class T> struct item_traits {};
template <> struct item_traits< Item<int> >
{
static int foo() { return 42; }
};
// ---------- end file "item.cpp" ----------
// ---------- begin file "main.cpp" ----------
#include <iostream>
#include "item.h"
int main()
{
Item<int> x;
std::cout << x.foo() << std::endl;
return 0;
}
// ---------- end file "main.cpp" ----------
The "Error" line implicitly instantiates the traits template, according
to ?14.7.1/1, so the code is ill-formed per ?14.7.1.2/6: "If an implicit
instantiation of a class template specialization is required and the
template is declared but not defined, the program is ill-formed."
Notice that the error occurs in main.cpp and the presence of the
explicit specialization in item.cpp (a different compilation unit) is
not enough because of ?14.7.3/6: "If a template, a member template or
the member of a class template is explicitly specialized then that
specialization shall be declared before the first use of that
specialization that would cause an implicit instantiation to take place,
in every translation unit in which such a use occurs; no diagnostic is
required."
Notice that, in this particular case, you can't just declare the
specialization item_traits<Item<int>>, because in order to use foo() you
also need the declaration of that! So you must provide the entire
definition of item_traits<Item<int>> in item.h (you don't need to
provide the definition of foo(), however).
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]