C++ 模板构造函数

时间:2023-04-25
本文介绍了C++ 模板构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我希望有一个带有不带参数的模板构造函数的非模板类.

I wish to have a non-template class with a template constructor with no arguments.

据我所知,这是不可能的(因为它会与默认构造函数冲突 - 我说得对吗?),解决方法如下:

As far as I understand, it's impossible to have it (because it would conflict with the default constructor - am I right?), and the workaround is the following:

class A{
   template <typename U> A(U* dummy) {
   // Do something
   }
};

也许有更好的替代方案(或更好的解决方法)?

Maybe there is a better alternative for this (or a better workaround)?

推荐答案

在调用构造函数模板时无法明确指定模板参数,因此必须通过参数推导来推导.这是因为如果你说:

There is no way to explicitly specify the template arguments when calling a constructor template, so they have to be deduced through argument deduction. This is because if you say:

Foo<int> f = Foo<int>();

是类型 Foo 的模板参数列表,而不是它的构造函数.构造函数模板的参数列表无处可去.

The <int> is the template argument list for the type Foo, not for its constructor. There's nowhere for the constructor template's argument list to go.

即使使用您的解决方法,您仍然必须传递参数才能调用该构造函数模板.根本不清楚您要实现的目标.

Even with your workaround you still have to pass an argument in order to call that constructor template. It's not at all clear what you are trying to achieve.

这篇关于C++ 模板构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:标准容器模板可以用不完整的类型实例化吗? 下一篇:使用模板进行隐式类型转换

相关文章

最新文章