What are C++'s rules regarding template specialization and namespace qualification? I had some code that boiled down to the equivalent of the following, and it made me realize that I don't understand C++'s rules regarding template specialization initializations. It seems weird to me firstly that the specializations of g::F<>
are even allowed inside h
, but given that, I don't know why things act the way they do.
namespace g {
struct N {
N(char c):c_(c){}
char c_;
};
template <typename V>
struct F {
static N n_s; // <-- want to initialize these for specializations
};
namespace h {
struct X { static constexpr char k{'x'}; };
template <> N F<char>::n_s{h::X::k}; // OK
template <> N F<int>::n_s{X::k}; // fails on "‘X’ not declared"
}
} // namespace g
// Seems weirdest to me. N and F need full qualifications but X doesn't.
template <> g::N g::F<float>::n_s{h::X::k}; // OK also!
The last instantiation/initialization, where the template static member initializer infers the g
namespace, makes it seem as though the template acts as though the initializer acts as though it were located in the same spot in code as the template definition itself.
What is the rule of the specification that dictates this behavior? (Note that this was tested on gcc 4.8.1, and looks thus far a bit like a bug...)
In:
It fails because the namespace associated with
F<int>::n_s
isg
, whereasX
is declared ing::h
. This is why you need to spell it out likeh::F<int>::n_s
.