Home C++ template - several specializations - is behaviour defined?
Reply: 0

C++ template - several specializations - is behaviour defined?

user9104
1#
user9104 Published in September 20, 2018, 8:43 pm

Let's imagine I declare a templated structure:

template <int N> struct mystruct;

Let's imagine my structure has a general behavior for all N, except when N == 0

I can declare for instance a special behavior for N == 0 with:

template<> struct mystruct<0> {int k = 0};

I can also declare the general behaviour with:

template<int N> struct mystruct {float k = 3.14;};

If I run in the main:

struct mystruct<-1> x;
struct mystruct<0> y;
struct mystruct<1> z;
std::cout << x.k << " " << y.k << " " << z.k << std::endl;

I get what I want : 3.14 0 3.14, whatever the order of template declarations.

However I am wondering if this behavior is insured. Indeed, when I declare:

struct mystruct<0> y;

In my mind, this could as well be defined by both mystruct implementations.

So the question is:

Does C++ normalization ensure the template specialization <0> to override the general basic implementation <int N>, whatever the templates specialization order in the code is?

share|improve this question
  • 6
    Short answer: Yes, that's the whole point of specializations. – DeiDei Feb 13 at 16:17
  • 1
    There is only one specialization here, mystruct<0>. The other variant is just a main template itself. – VTT Feb 13 at 16:17
  • 1
    It's guaranteed, as long as it can see it. You can have very real situations where you have some primary template, a header that specializes it for some type Foo, and then some client of this primary template somehow doesn't include the header doing the specializing behavior. If the primary and specializations are all in one header, this can't happen, but it can come up often when template specialization is used as a customization point for libraries. Thought, careful design, and documentation for your users is required for this sort of thing. – Nir Friedman Feb 13 at 16:24

2 Answers 2

active oldest votes
up vote 5 down vote
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.305072 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO