Possible to access private types in base classes via template indirection
Asked Answered
D

1

4

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.

Dugald answered 22/7, 2013 at 16:28 Comment(9)
Please provide an SSCCE (and perhaps find a better title?!)Nils
@stefan, it is - the code should compile, I left out two header inclusions for brevity...Dugald
still lacking #include <string> and a semicolon after a struct. That's not an SSCCE.Nils
Additionally I don't get what's unexpected to you. Can you please also provide generated output and expected / wanted output?Nils
As I said before, is a SSCCE, it doesn't need string; I typed out the code (can't copy/paste) and the only omission was a ;, else it compiles fine. ideone.com/9YJWIu The unexpected was that, 1. it compiles and 2. the output is prefixed with "A: " both of which I mention already in the question... I would have expected a compiler error, as you get if you try to use the type directly...Dugald
Of course it needs <string>, it's using std::string. The fact that either <iostream> or <type_traits> pulls in <string> on your implementation does not imply that it does on every implementation.Herbart
Here is a real sscce.org : ideone.com/JRHFS2 -- here I used std::conditional to get at a type I have no business accessing.Junie
@Casey, I tagged the question gcc4.7, it works on my implementation, if yours needs it, your compiler will tell you. This is a major distraction from the main question which still stands, is this legal or illegal... I'm erring on a GCC bug, but it would be nice to know...Dugald
@Dugald I don't know: I just reduced it to the point where we can ask the question, not the point where we have the answer.Junie
S
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.
Sulfathiazole answered 23/7, 2013 at 11:0 Comment(2)
Hi, thanks for the answer. I knew my test was flawed, I just hadn't got around to fixing it correctly, before I was hit by this bug. The "bug" actually helps in this case as with a simple template indirection, I can get a whole inheritance hierarchy to use the same logger or fail to the global logger! But, it's a bug that I cannot exploit.. :) The only issue I have with the approach you've taken is that I need to template the test with the type (A, B etc.) which is problematic in a generic macro (such as ERROR, WARNING) which can be in any code...Dugald
that is not a problem :) -- you may require from any type, which has an its own Log to provide a typedef A this_class; and use this_class alias in your macro...Sulfathiazole

© 2022 - 2024 — McMap. All rights reserved.