简体   繁体   English

从具有模板化构造函数的非模板化类继承 - 如何解决歧义?

[英]Inheriting from a non-templated class that has a templated constructor - how to resolve ambiguity?

Let's say we have a class, MyParent: 假设我们有一个类,MyParent:

class MyParent
{
public:
  template<namespace T>
  MyParent()
  {
    T* Something;
  }
};

And a derived class, which uses this constructor: 和派生类,它使用这个构造函数:

class MyDerived : public MyParent
{
public:
  MyDerived()
  : MyParent<int>()
  {
  }
};

Then I get a compiling error, because there's ambiguity. 然后我得到一个编译错误,因为它有歧义。 The compiler thinks that the int is a template argument to the class, not the constructor. 编译器认为int是类的模板参数,而不是构造函数。

How do I specify that I want the int to be an argument to the constructor? 如何指定我希望int成为构造函数的参数?

It is not possible. 这不可能。 From the standard section 14.8.1 Explicit template argument, it notes: 从标准部分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. [注意:因为显式模板参数列表遵循函数模板名称,并且因为在不使用函数名称的情况下调用转换成员函数模板和构造函数成员函数模板,所以无法为这些函数模板提供显式模板参数列表。 ] ]

As noted in the comments, you would need to have the constructor take a parameter of type T (or const T & ), and then have MyDerived call MyParent::MyParent with a paremeter of type int . 如注释中所述,您需要让构造函数采用类型为T (或const T & )的参数,然后使用类型为int的参数调用MyDerived调用MyParent::MyParent

Note that your question is not particular to inheritance. 请注意,您的问题并不特定于继承。 Given your code example, you cannot instantiate MyParent at all, either because it doesn't accept a template argument list or because it has no default constructor. 鉴于您的代码示例,您根本无法实例化MyParent ,因为它不接受模板参数列表,或者因为它没有默认构造函数。

In order to instantiate MyParent with a constructor template, you need to provide some way for the compiler to know the template argument, and you can't do that with a no-argument constructor. 为了使用构造函数模板实例化MyParent ,您需要为编译器提供一些知道模板参数的方法,而不能使用无参数构造函数。 You need to give MyParent 's constructor a parameter. 你需要给MyParent的构造函数一个参数。 Here's an example based on code from Alf P. Steinbach : 以下是基于Alf P. Steinbach代码的示例:

template <typename T>
struct UseMethodsOf {};

class MyParent
{
public:
  template <typename T>
  MyParent(UseMethodsOf<T>)
  {
    T* Something;
  }
};

class MyDerived: public MyParent
{
public:
  MyDerived()
  : MyParent(UseMethodsOf<int>())
  {
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM