2

I'm currently writing a program, which shares a lot of template structures in one of the header files. To evaluate those templates, I use some other helper structures, like here:

#define MAX 10

struct function1 {
    static constexpr int f(int x) {
        return x*(x*x+20);
    }
};

struct function2 {
    static constexpr int f(int x) {
        return (x*x+20);
    }
};

// This structure contains supremum of function contained in
// type T, on interval (0, MAX). We're assuming that f(0) is 0
// for each function class passed in T.
template <typename T>
struct supremum {
    static constexpr int valueF(int n) {
        return n == 0 ? 0 : (T::f(n) > T::f(n-1) ? n : valueF(n-1));
    }
    static constexpr int value = valueF(MAX);
};

template <typename T1, typename T2>
struct supremums {
    static constexpr int s1 = supremum<T1>::value;
    static constexpr int s2 = supremum<T2>::value;
};

// Sample struct initialization
supremums<function1, function2> s;

So this is my header file - the problem is that I want to share structure supremums to users using it , but I don't want to do that with helper structure supremum. Is there a way to hide supremum from "the outside"?

Sorry, I just noticed these supremum structures are not valid, but these are only examples on which I wanted to show a specific problem, so their validity is not an issue.

qiubit
  • 4,708
  • 6
  • 23
  • 37

1 Answers1

4

Since templates are usually implemented in header files, you cannot normally hide them from a user if they want to snoop.

The best you can do is put them in a namespace, such as detail or impl_detail and document them as being implementation details. Hopefully users of your header file will pay heed to the documentation and not use anything under that namespace.

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 2
    Well, from your link it appears that *must* is a bit exaggerated, even though I agree that that's the most common approach and a widely used one. – skypjack Dec 02 '15 at 00:00
  • @skypjack, can you provide counter examples that refute the *must* claim? – R Sahu Dec 02 '15 at 02:39
  • 1
    @R Sahu see the first answer from the question you pointed out and also this [link](https://isocpp.org/wiki/faq/templates) for further details. – skypjack Dec 02 '15 at 06:51
  • 2
    @R Sahu Please, note also that I agree with you on the fact that he has no much chances in this case, for he wants to export them in a public API. Anyway, to say *templates must be implemented in header files* is some how wrong, for you can work around it in some cases. Can you? Yes. Would I do that? No. That's for the sake of clarity anyway. :-) – skypjack Dec 02 '15 at 07:03
  • @skypjack, I read the C++ FAQ link. I see what you are saying. Let me rephrase the answer. – R Sahu Dec 02 '15 at 07:04
  • 1
    @skypjack, thanks for being patient with me while I educated myself :) – R Sahu Dec 02 '15 at 07:09