c++ - 在派生类中初始化具有依赖类型名称的基子对象

标签 c++ c++11 typetraits

给定此示例代码,其类 C 根据策略派生自 AB

#include <iostream>
#include <type_traits>

struct A
{
    A(int a) { std::cout << a << "\n"; }
};

struct B
{
    B(int a) { std::cout << -a << "\n"; }
};

template<bool>
struct policy;

template<>
struct policy<true> { typedef A type; };

template<>
struct policy<false> { typedef B type; };

template<typename T>
struct C : public policy<std::is_polymorphic<T>::value>::type
{
    C() : /* ????? */(5) {}
};

int main()
{
    C<int> a; // should print -5
    C<std::ostream> b; // should print 5
}

如何初始化C的基类? (或者,如果不可能,是否有解决方法?)

最佳答案

按照找到 C 的基类的方式进行操作:

template<typename T>
struct C : public policy<std::is_polymorphic<T>::value>::type
{
    C() : policy<std::is_polymorphic<T>::value>::type(5) {}
};

当然,为了使其更具可读性,您还可以添加一个typedef(也许您会在 C 内多次需要基类,那么这是值得的)。这看起来像这样:

template<typename T>
struct C : public policy<std::is_polymorphic<T>::value>::type
{
    typedef typename policy<std::is_polymorphic<T>::value>::type Base;
    C() : Base(5) {}
};

为了让它不那么丑陋,您还可以添加另一层间接寻址,例如模板类 BaseForC产生正确的基数 BaseForC<T>::type并封装了policyis_polymorphic现在正在做一节课。

关于c++ - 在派生类中初始化具有依赖类型名称的基子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26351199/

相关文章:

c++ - 如何知道 std::thread 在 C++ 中何时完成?

c++ - 在 C++ 中遍历一个字符串

c++ - 使用模板进行递归类型检查

c++ - Visual C++ 中与 reverse_iterator 相关的崩溃。是合法代码吗?

c++ - Qt5 - 未找到 Windows : VCRUNTIME140D_APP. dll

c++ - 在 Windows 上列出 *.lib 中的函数

python - Chrome native 消息传递不接受特定大小的消息 (Windows)

c++11 - 使用 C++11 的 MinGW 和压缩结构对齐

c++ - 检查类型是否在可变参数模板参数包中传递

c++ - 概念可能会取代 C++ 中的类型特征吗?