C ++模板构造函数 [英] C++ template constructor

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

问题描述

我希望有一个非模板类和一个没有参数的模板构造函数。

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>();

< 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 ++模板构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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