使用不带模板参数的模板类 [英] using a template class without a template argument

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

问题描述

我有一个Visual Studio 2008 C ++项目与一个模板类,在构造函数中采用模板化的值如下:

I have a Visual Studio 2008 C++ project with a template class that takes the templated value in the constructor like this:

template< typename A >
struct Foo
{
    const A& a_;
    Foo( const A& a ) : a_( a ) { };
};

因此,我必须这样构造这个类:

Therefore, I have to construct this class like this:

int myval = 0;
Foo< int > foo( myval );

似乎多余的必须指定 int 作为模板参数,当它已经在构造函数中指定。我想要一些方法使用它像这样:

It seems redundant to have to specify int as a template parameter when it's already specified in the constructor. I'd like some way to use it like this:

Foo foo( myval );



现在,我得到编译器错误:

As is, I get the compiler error:

error C2955: 'Foo' : use of class template requires template argument list


b $ b

感谢,
PaulH

Thanks, PaulH

推荐答案

如果你命名类型,完整类型(即 Foo ,而不仅仅是 Foo )。

If you name the type at all, it has to be the complete type (i.e., Foo<int> and not just Foo).

一个类可以有多个构造函数,也可能没有构造函数具有类模板的type参数的参数,所以没有办法使它适用于所有的类模板在我看来,有时,但不是所有的时间,这个工作将是困惑的)。

A class can have multiple constructors or may have no constructors that have a parameter of the class template's type parameter, so there's no way to make this work for all class templates (in my opinion it would be confusing to have this work sometimes but not all the time).

如果你没有命名的类型,你可以写一个 MakeFoo< T>()构造一个 Foo 的函数模板并使用函数模板参数扣除:

If you are okay not naming the type at all, you can write a MakeFoo<T>() function template that constructs a Foo<T> and use function template argument deduction:

template <typename A>
Foo<A> MakeFoo(const A& a) { return Foo<A>(a); }

这种模式通常用于C ++(参见例如 make_shared )。

This pattern is commonly used in C++ (see, for example, make_shared).

如果要将返回的对象存储在变量中,那么该变量仍需要一个类型。如果你能够移动到支持C ++ 0x的 auto (如Visual C ++ 2010)的编译器,那么你可以使用它。否则,您可以使用第三方解决方案,例如 BOOST_AUTO 或者写自己的(虽然这可能会有很多工作( - :)。

If you want to store the returned object in a variable, though, that variable still needs to have a type. If you are able to move to a compiler that supports C++0x's auto (like Visual C++ 2010), then you can use that. Otherwise, you can use a third-party solution like BOOST_AUTO or write your own (though that would likely be quite a lot of work (-: ).

使用 auto ,您的代码将如下所示:

With auto, your code would look like:

auto foo(MakeFoo(myval));

这篇关于使用不带模板参数的模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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