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
247 views
in Technique[技术] by (71.8m points)

c++ - Problem on declaring friend function with type traits in a class

I'm playing around with the singleton pattern in C++, and want to implement an global function that completes the construction of a class. I used std::is_base_of in that function, but that makes it impossible for me to declaring the function in the class.

Here's a short example:

#include <type_traits>
class A {};

template<typename T>
typename std::enable_if_t<std::is_base_of_v<A, T>, T*>
Instance() { return T(); }

template<typename T>
typename std::enable_if_t<!std::is_base_of_v<A, T>, T*>
Instance() { return T(); }

class B : public A {
 protected:
    B();
    friend B* Instance<B>();  // Error
};

The above code will cause "invalid use of incomplete type" using gcc or C2139 using MSVC when instantiating the first function.

So, other than making constructor B::B() to be public, is there any possible way for me to work around with it?

question from:https://stackoverflow.com/questions/65861488/problem-on-declaring-friend-function-with-type-traits-in-a-class

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

1 Reply

0 votes
by (71.8m points)

Issue is that during definition of class, the class is still incomplete,

and std::is_base_of required complete type for Derived, else you have UB.

If you have access to C++17, you might do:

template<typename T>
T* Instance() {
    if constexpr (std::is_base_of_v<A, T>) {
        return nullptr; // Your impl
    } else {
        return nullptr; // Your impl
    }
}

class B : public A {
 protected:
    B();
    friend B* Instance<B>();
};

Demo


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

...