Index: gcc/cp/pt.c
===================================================================
--- gcc/cp/pt.c	(revision 164893)
+++ gcc/cp/pt.c	(working copy)
@@ -1379,6 +1379,11 @@ register_specialization (tree spec, tree
 	}
       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
 	{
+	  /* A specialization must be declared in the same namespace as the
+	     template it is specializing.  */
+	  if (!check_specialization_namespace (tmpl))
+	    return error_mark_node;
+
 	  if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
 	    /* Dup decl failed, but this is a new definition. Set the
 	       line number so any errors match this new
Index: gcc/testsuite/g++.dg/template/pr42018.C
===================================================================
--- gcc/testsuite/g++.dg/template/pr42018.C	(revision 0)
+++ gcc/testsuite/g++.dg/template/pr42018.C	(revision 0)
@@ -0,0 +1,14 @@
+// PR c++/42018
+// { dg-do compile }
+
+template<typename>
+  void foo(void);             // { dg-error "from definition of" }
+
+template<>
+  void foo<int>();
+
+namespace x {
+  template<>
+    void foo<int>() { return; } // { dg-error "in different namespace" }
+}
+
