C++:在编译时消除此代码的歧义



我试图找到一种方法来消除这段代码的歧义(在编译时)(因为两天:-)->get_value是模糊的。

#include <iostream>
template <typename T>
struct type2type {};
template<class T, int val>
struct BASE
{
  static constexpr int get_value ( type2type< T > )
  {
    return val;
  }
};
class X {};
class Y {};
struct A :
  public BASE< X, 1 >,
  public BASE< Y, 0 >
{};
int main ( int argc, char **argv )
{
  A a {};
  std::cout << a.get_value ( type2type< X >{} ) << std::endl;
}

这是一个有效的运行时解决方案。

#include <iostream>
template <typename T>
struct type2type {};
template<class T>
struct VIRTUAL
{
  int get_value () const
  {
    return get_value_from_BASE ( type2type< T > {} );
  }
private:
  virtual int get_value_from_BASE ( type2type< T > ) const = 0;
};
template<class T, int val>
class BASE :
  public VIRTUAL< T >
{
  virtual int get_value_from_BASE ( type2type< T > ) const override
  {
    return val;
  }
};
class X {};
class Y {};
struct A :
  public BASE< X, 1 >,
  public BASE< Y, 0 >
{};
int main ( int argc, char **argv )
{
  A a {};
  std::cout << a.::VIRTUAL< X >::get_value () << std::endl;
}

有解决方案吗?

注意:我发现的一种可能的方式是超过std::is_base_of<>,但这是非常有限的(模板实例化深度)

这是一个不明确的名称查找,在多重继承的情况下,它会隐藏查找中的名称。它甚至没有检查使用哪个过载。

您可以通过在struct A的定义中添加以下内容来解决此问题:

using BASE<X,1>::get_value;
using BASE<Y,0>::get_value;

这两条语句将两个基类中的名称get_value添加到A中,因此编译器可以继续其沉闷的生活,并将它们作为重载进行检查。

基于Atash的答案:假设您不想在基类列表和using声明中重新键入基类列表,那么您可以使用这样的间接方法:

#include <iostream>
template <typename T>
struct type2type {};
template<class T, int val>
struct BASE
{
  static constexpr int get_value ( type2type< T > const& )
  {
    return val;
  }
};
class X {};
class Y {};
template <typename...> struct AUX;
template <typename Base, typename... Bases>
struct AUX<Base, Bases...>: Base, AUX<Bases...> {
    using Base::get_value;
    using AUX<Bases...>::get_value;
};
template <typename Base>
struct AUX<Base>: Base {
    using Base::get_value;
};
struct A :
    public AUX<BASE< X, 1 >, BASE< Y, 0 > >
{
};
int main ()
{
  A a {};
  std::cout << a.get_value ( type2type< X >() ) << std::endl;
}

最新更新