c++ - 派生自模板基类的模板构造函数

标签 c++ templates inheritance c++11

只是好奇,是否有可能从模板类继承并在派生类的构造函数中调用基类的构造函数,该基类也是模板化的并且没有参数可从中推断其类型?

template<typename T>
struct Base {
    template<typename D>
    Base() {                // no argument of type D to infer from
        static_assert(std::is_same<T,D>::value, "");
    }
};

struct Derived : Base<int> {
    Derived()  : Base<int>::Base<int>() {} // is there a way to write it correctly?
};

在我的特定情况下,我可以用模板方法替换模板构造函数,但这仍然是一个关于语言灵 active 的有趣问题。

最佳答案

C++ 标准对此有何规定(第 14.8.1 节):

[ Note: Because the explicit template argument list follows the function template name, and because conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for these function templates. — end note ]

这是一个注释,而不是规则,因为它实际上是其他两个规则的结果,一个在同一部分:

Template arguments can be specified when referring to a function template specialization by qualifying the function template name with the list of template-arguments in the same way as template-arguments are specified in uses of a class template specialization.

从 12.1 开始

Constructors do not have names.

关于c++ - 派生自模板基类的模板构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26553803/

相关文章:

php - 无法为 OS X 10.9.5 安装 Sphinx : '"/lib/cpp"fails sanity check'

c++ - 如何使 boost::log::keywords::file_name 使用 UTC 时间?

c++ - 不熟悉模板的结构/类声明

c++ - 未使用依赖类型的“预期主表达式”错误

c++ - 为什么数据成员不继承菱形继承(钻石问题)c++

java - java.sql.Timestamp 的 javadoc 中的实现继承是什么意思?

c++ - 如何在链表类中实现赋值运算符

c++ - 在 g++ 中链接文件

css - 将 CSS 添加到 Joomla 3 模板管理区域

c++ - 从子类中隐藏变量