Possible to access private types in base classes via template indirection

不羁岁月 提交于 2019-12-22 09:05:37

问题


I'm trying to, at compile time, select a type to use depending on whether one is publicly available in a given scope. It's best to go straight to the code:

#include <iostream>
#include <type_traits>

class Logger
{
  std::string _p;
public:
  Logger(std::string p): _p(p)
  { }

  void say(std::string message)
  { std::cout << _p << ' ' << message << std::endl; }
};

struct Log
{
  static Logger& log()
  {
    static Logger _def("Default: ");
    return _def;
  }
};

// 1.
template <typename P>
struct use_logger
{
  static std::size_t test(P*);
  static char test(...);
  static const bool value = sizeof(test(reinterpret_cast<P*>(0))) == sizeof(std::size_t);
};

class A
{
  struct Log
  {
    static Logger& log()
    {
      static Logger _def("A: ");
      return _def;
    }
  };
public:

  void say()
  {
    std::cout << "A: " << use_logger<Log>::value << std::endl;
    std::conditional<use_logger<Log>::value, Log, ::Log>::type::log().say("From A");
  }
};

class B
{
public:

  void say()
  {
    std::cout << "B: " << use_logger<Log>::value << std::endl;
    std::conditional<use_logger<Log>::value, Log, ::Log>::type::log().say("From B");
  }
};

class C : A
{
public:

  void say()
  {
    std::cout << "C: " << use_logger<Log>::value << std::endl;
    //2.
    std::conditional<use_logger<Log>::value, Log, ::Log>::type::log().say("From C");
    // Log::log().say("From C");
  }
};

class D : public A
{
public:

  void say()
  {
    // 2.
    std::cout << "D: " << use_logger<Log>::value << std::endl;
    std::conditional<use_logger<Log>::value, Log, ::Log>::type::log().say("From D");
    // Log::log().say("From C");
  }
};

int main(void)
{
  {
    A i;
    i.say();
  }
  {
    B i;
    i.say();
  }
  {
    C i;
    i.say();
  }
  {
    D i;
    i.say();
  }
}

My intention is that in A, there is a type Log, so that should be used rather than the global ::Log, and in B where there is none, it should use the global ::Log. Now both these work irrespective of 1. (my incorrect test to see if the type is private in this scope..)

The problem is in C and D, normally - without the test, Log::log() fails, because it's private in A. However if the std::conditional<> is used, there is no compilation error, and the output is incorrect as it is prefixed with A:. So, what have I missed (apart from the incorrect test - which I need to somehow fix...)? If nothing, then is this approach of exposing the private type in A using the std::conditional legal?

EDIT: for sanity, I tested with the following:

std::conditional<false, Log, ::Log>::type::log("From C");
std::conditional<false, Log, ::Log>::type::log("From D");

And it does use the global ::Log, if it's true, it's somehow using the private A::Log.

EDIT2: Infact this appears to be a more general condition, i.e. you can easily get access to some internal private types via a template indirection, e.g:

class F
{
  struct Foo
  {
    void bar() { }
  };
};

template <typename T>
struct ExposeInternal
{
  typedef T type;
};

int main(void)
{
  {
    // We've got Foo!
    ExposeInternal<F::Foo>::type t;
    t.bar();
  }
  {
    // Below fails
    F::Foo t;
    t.bar();
  }
}

EDIT 3: Okay - have confirmed, it is a reported GCC bug, nothing to do with std::conditional, not yet fixed in 4.7 or 4.8. http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47346

I will leave this question open for the moment.. will close it with the above later.


回答1:


I've modified your example a little, so w/ my gcc 4.8.1 now everything work as expected (intended).

Few notes about original code:

  • when you wanted to test accessibility of a Log (using use_logger) the primary misunderstanding that use_logger is an external class for A, B, C, D! It can't (by design) to access anything 'cept public members of that classes!
  • the second aspect about your checker: passing the type Log into it, you going to loose "context" -- i.e. the checker doesn't know (and it have no way to realize it w/ that design) "is this type is actually a nested type of something else?"
  • and finally use_logger just incorrect: it always reinterpret 0 to a P* -- there is no other possibilities (ways to interpret) this code... the main idea behind such checkers is to form a set of "matched" functions, then, at instantiation time, compiler will remove inappropriate by SFINAE (and "fallback" to a generic test(...) overload) or accept some as most suitable from result overload set. Your test(P*) just always relevant! -- It is why it doesn't choose anything actually...

so, here is my code:

#include <iostream>
#include <string>
#include <type_traits>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>

class Logger
{
    std::string _p;
public:
    Logger(std::string p): _p(p)
    { }

    void say(std::string message)
    {
        std::cout << _p << ' ' << message << std::endl;
    }
};

struct Log
{
    static Logger& log()
    {
        static Logger _def("Default: ");
        return _def;
    }
};

namespace details {
/// Helper class to check availability of a nested type \c Log
/// whithing \c T and it's static function \c log()
struct has_nested_logger_available_checker
{
    typedef char yes_type;
    typedef char (&no_type)[2];

    template <typename T>
    static no_type test(...);

    template <typename T>
    static yes_type test(
        typename std::add_pointer<
            decltype(std::is_same<decltype(T::Log::log()), Logger>::value, void())
        >::type
    );
};
}

/// Metafunction (type trait) to check is a nested type \c Log accessible
template <typename T>
struct has_nested_logger_available : std::is_same<
    decltype(details::has_nested_logger_available_checker::template test<T>(nullptr))
, details::has_nested_logger_available_checker::yes_type
>
{};

template <typename T>
struct access_nested_logger
{
    typedef typename T::Log type;
};

template <typename T>
struct logger_chooser : public boost::mpl::eval_if<
        has_nested_logger_available<T>
    , access_nested_logger<T>
    , boost::mpl::identity<::Log>
    >
{
};

class A
{
/// \attention I suppose original code has a typo here:
/// anything in a \c private section being inherited will be
/// \b inaccessible to a child with \c all kind of inheritance!
/// So if latter we want to use it from \c D, it \b must be at least
/// \c protected.
protected:
    struct Log
    {
        static Logger& log()
        {
            static Logger _def("A: ");
            return _def;
        }
    };

    /// \attention Checker and accessor \c MUST be a friend of this class.
    /// Cuz being called from \c A::say (which is actually a member, so it
    /// has full access to other members), it must have \b the same access
    /// as other (say) member(s)!!!
    friend struct details::has_nested_logger_available_checker;
    /// \todo Merge (actual) checker and "accessor" to the same class to
    /// reduce code to type... (a little)
    friend struct access_nested_logger<A>;

public:
    void say()
    {
        std::cout << "A: " << has_nested_logger_available<A>::value << std::endl;
        logger_chooser<A>::type::log().say("From A");
    }
};

class B
{
public:
    void say()
    {
        std::cout << "B: " << has_nested_logger_available<B>::value << std::endl;
        logger_chooser<B>::type::log().say("From B");
    }
};

class C : A
{
public:
    void say()
    {
        std::cout << "C: " << has_nested_logger_available<C>::value << std::endl;
        logger_chooser<C>::type::log().say("From C");
    }
};

/// With \c public inharitance, \c D can access \c public and/or \c protected
/// members of \c A. But not \c private !!!
class D : public A
{
public:
    /// \sa \c A
    friend struct details::has_nested_logger_available_checker;
    friend struct access_nested_logger<D>;

    void say()
    {
        std::cout << "D: " << has_nested_logger_available<D>::value << std::endl;
        logger_chooser<D>::type::log().say("From D");
    }
};

int main(void)
{
    {
        A i;
        i.say();
    }
    {
        B i;
        i.say();
    }
    {
        C i;
        i.say();
    }
    {
        D i;
        i.say();
    }
    return 0;
}

the output:

zaufi@gentop /work/tests $ g++ -std=c++11 -o so_log_test so_log_test.cc
zaufi@gentop /work/tests $ ./so_log_test
A: 1
A:  From A
B: 0
Default:  From B
C: 0
Default:  From C
D: 1
A:  From D

zaufi@gentop /work/tests $ g++ --version
g++ (Gentoo 4.8.1 p1.0, pie-0.5.6) 4.8.1
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software
see the source for copying conditions.  There is NO
warranty
not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


来源:https://stackoverflow.com/questions/17792751/possible-to-access-private-types-in-base-classes-via-template-indirection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!