4

Possible Duplicate:
How to allow template function to have friend(-like) access?

How do I give function template Load friend access to class Foo?

The objective here is to restrict access to the constructor: only function template Load may construct.

CODE (please ignore memory leak)

class Foo { 
    Foo() { } 

    template<> friend Foo const& Load<Foo>();   // error here
};

template<typename T>
T const&
Load() { return *(new T); }

int main( int argc, char* argv[] )
{
    Foo const& f = Load<Foo>();
}
Community
  • 1
  • 1
kfmfe04
  • 14,936
  • 14
  • 74
  • 140
  • @WhozCraig - I found that before posting this, but have you tried to actually READ through that insane post? I think the scope of that one is beyond the simplicity of this one. – kfmfe04 Dec 23 '12 at 06:07
  • You don't, actually and in fact, I'm not sure even the answers *here* are what you really want. Do you want that template function to have access to your class, but only the specialization where your class is the T-type param ? It may seem an odd question, but it is important. If so, iagreen's answer is pretty solid. – WhozCraig Dec 23 '12 at 06:08
  • @WhozCraig - wouldn't iagreen's solution below work? I think the scope of that one should be limited. – kfmfe04 Dec 23 '12 at 06:10
  • @kfmfe04 not the issue of scope, friend template is declaration... – billz Dec 23 '12 at 06:12
  • It should be fine. the syntax is a little different if your class is also a template, but yours is not, so his will work very well for you. I'm more used to `friend Foo const& Load<>();` – WhozCraig Dec 23 '12 at 06:25

2 Answers2

3

This should work.

template<typename T> T const& Load() { return *(new T); }


    class Foo {
        Foo() { } 

        friend Foo const& Load<Foo>();
    };
iagreen
  • 31,470
  • 8
  • 76
  • 90
  • +1 looks good - makes sense - seems like forward-declaration of function template is sufficient for Foo to compile. – kfmfe04 Dec 23 '12 at 06:06
2

Doing it like this should work:

#include <iostream>

template <typename T>
const T&
load(void)
{
    return *(new T);
}

class foo
{
    private:                                                                                                                                                                                                                                                                                                          
        foo(void)
        {
            std::cout << "hello!" << std::endl;
        }
    template <typename T>
        friend const T& load();
};

int
main(void)
{
    const foo& f = load<foo>();
    return 0;
}
cmc
  • 2,061
  • 1
  • 19
  • 18