c++ - 如何解决,在使用元编程的条件基类的情况下没有成员函数 "print"

标签 c++ inheritance metaprogramming template-meta-programming

.header

template<class T>
struct type_is
{
 using type = T; 
};

template<bool, class T, class>
struct IF_t : type_is<T> {};

template<class T, class F>
struct IF_t<false, T, F> : type_is<F> {};

class Base1
{
public:
void print()
{
    std::cout << "Base 1" << std::endl;
}
};

class Base2
{
public:
void print()
{
    std::cout << "Base 2" << std::endl;
}
};

template <int q>
class Derived : IF_t<(q > 0), Base1, Base2>
{
};

class MultipleBaseTemplateMetaProg {
public:
void print()
{
    Derived<1> aDerivedTrue;
    aDerivedTrue.print();
    Derived<-1> aDerivedFalse;
    aDerivedFalse.print();
}
};

main.cpp

 MultipleBaseTemplateMetaProg aMetaProg;
 aMetaProg.print();

我的问题是,当我尝试调用 print() 时。我收到错误消息说 print 不是成员函数。我也不能在派生类中使用“使用”来声明打印。

有什么办法可以解决这个问题吗?除了创建一个公共(public)基类之外?

最佳答案

尝试替换 class Derived : IF_t<...>class Derived : public IF_t<...>::type . Derived派生自 IF_t而不是 Base1Base2 .它还需要公开,以便您可以访问 Base1/Base2来自 Derived 的函数.

关于c++ - 如何解决,在使用元编程的条件基类的情况下没有成员函数 "print",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35998368/

相关文章:

c++ - 如何使用模板创建排序映射整数索引

Ruby 元类疯狂

c++ - 通过元编程将 c++ 简化为objective-c/cocoa 桥接?

c++ - OpenCV:计算相机和像素之间的角度

c++ - opengl中如何用鼠标点击获取帧缓冲区中绘制图形的像素信息

c++ - 静态 constexpr 全局变量

c++ - boost::geometry::read_wkt 替代方案?

c++ - 为什么编译器会尝试将指针传递给引用而不是此代码片段中的指针?

c++ - 使用基类静态常量变量构造基类,我可以这样做吗?

java - 如何将下面的示例转换为实现 Runnable 接口(interface)并重写 run 方法