gpt4 book ai didi

c++ - 使用没有模板参数的模板类

转载 作者:太空狗 更新时间:2023-10-29 19:46:52 24 4
gpt4 key购买 nike

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

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

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

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

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

Foo foo( myval );

按原样,我得到编译器错误:

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

谢谢,保罗H

最佳答案

C++17 修复了这个问题,引入了template argument deduction for constructors .

引用 Herb Sutter :

[...] you can write just pair p(2, 4.5); instead of pair<int,double> p(2, 4.5); or auto p = make_pair(2, 4.5);. This is pretty sweet, including that it obsoletes many “make” helpers.

关于c++ - 使用没有模板参数的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6388844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com