Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

c++ - declare template friend function of template class

I have a class template Obj and a function template make_obj. Obj has a private single constructor defined, which takes a reference to its templated type to bind to.

template <typename T>
class Obj {
  private:
    T& t;
    Obj(T& t)
        : t{t}
    { }
};

template <typename T>
Obj<T> make_obj(T& t) { 
    return {t};
}

What I want is to declare the make_obj function a friend so that it can create Obj's, but no one else can (except via the copy ctor).


I have tried several friend declaration including

friend Obj make_obj(T&);

and

template <typename T1, typename T2>
friend Obj<T1> make_obj(T2&);

The latter being a less than desirable attempt at making all template instantiations of make_obj friends of the Obj class. However in both of these cases I get the same error:

error: calling a private constructor of class 'Obj<char const[6]>'
    return {t};
           ^

note: in instantiation of function template specialization
      'make_obj<const char *>' requested here
    auto s = make_obj("hello");
             ^

trying to do make_obj("hello"); for example purposes.

How can I allow only make_obj access to Obj's value contructor?

question from:https://stackoverflow.com/questions/18792565/declare-template-friend-function-of-template-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need a few forward declarations:

template <typename T>
class Obj;

template <typename T>
Obj<T> make_obj(T t);

template <typename T>
class Obj {
private:
    T & t;
    Obj (T & t) : t(t) { }
    Obj() = delete;

    friend Obj make_obj<T>(T t);
};

template <typename T>
Obj<T> make_obj(T t) { 
    return Obj<T>(t);
}

live example

And BTW: I don't think you really want T & t; for your class' member variable. Probably T t; is a better choice ;)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...