从模板基类的模板const派生 [英] Derive from template constuctor of template base class

查看:106
本文介绍了从模板基类的模板const派生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是好奇,是否有可能继承一个模板类,并在派生类的构造函数中,基类的调用构造函数也是模板化的,没有参数来推导它的类型?

 模板< typename T> 
struct Base {
template< typename D>
Base(){//类型D的参数从
推断static_assert(std :: is_same< T,D> :: value,);
}
};

struct Derived:Base< int> {
Derived():Base< int> :: Base< int>(){} //有没有办法正确写入?
};



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

解决方案

C ++标准对此有什么说明(第14.8.1节):


[注意:因为显式模板参数列表跟在函数模板名称后面,并且因为调用了转换成员函数模板和构造函数成员函数模板而不使用函数名,没有办法为这些函数模板提供显式的模板参数列表。 - end note]


这是一个注释,而不是规则,因为它实际上是另外两个规则的结果,


通过使用模板参数列表来限定函数模板名称,当引用函数模板专用化时,可以指定模板参数


和从12.1

$ b $

中指定模板参数的方式相同。



Just curious, is it ever possible to inherit from a template class and in constructor of the derived class, call constructor of the base class which is also templated and has no arguments to deduce its types from?

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?
};

I can replace template constructor by a template method in my particular case, but still it is an interesting question about the language flexibility.

解决方案

What the C++ standard says about this (section 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 ]

It's a note, not a rule, because it actually is a consequence of two other rules, one in the same section:

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.

and from 12.1

Constructors do not have names.

这篇关于从模板基类的模板const派生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆