简体   繁体   English

可变参数模板和通过赋值构造副本

[英]Variadic templates and copy construction via assignment

Consider this minimal example: 考虑以下最小示例:

template <typename T, typename U>
struct foo {};

template <template <typename...> class Bar>
struct converter
{
     template <typename... Args>
     converter(const Bar<Args...> &);
};

int main()
{
    converter<foo> c(foo<int,double>()); // This works.
    // converter<foo> c = foo<int,double>(); This fails
}

The commented-out line fails with both GCC 4.5 and 4.6, with a message like: 在GCC 4.5和4.6中,注释掉的行均失败,并显示以下消息:

main.cpp:10:2: error: wrong number of template arguments (1, should be 2)
main.cpp:4:8: error: provided for template<class T, class U> struct foo
main.cpp: In function int main():
main.cpp:15:37: error: conversion from foo<int, double> to non-scalar type converter<foo> requested

If, instead of using variadic templates, the specific number of template parameters is used (ie, 2 in this case) there are no errors. 如果不是使用可变参数模板,而是使用特定数量的模板参数(在这种情况下为2),则没有错误。 I'm a bit confused since I expected the two lines to be exactly equivalent: is this an expected behaviour? 我有点困惑,因为我希望这两行完全相同:这是预期的行为吗?

Yes, this is supposed to work. 是的,这应该可行。 It's a GCC error. 这是GCC错误。 GCC doesn't support C++0x variadic templates to the fullest yet (and to be fair, the specification is still constantly changing in details). GCC尚未完全支持C ++ 0x可变参数模板(公平地说,规范在细节上仍在不断变化)。

What you say "This works" is really declaring a function; 您所说的“这有效”实际上是在声明一个功能。 it doesn't initialize an object, which was what you intended. 它不会初始化对象,这正是您想要的。

For what you intended, see 14.3.3p3 which describes how template<typename...> class Bar can match foo , and 14.8.2.5p9 which describes how foo<Args...> can match foo<int, double> . 对于您想要的内容,请参见14.3.3p3,它描述template<typename...> class Bar如何匹配foo ,以及14.8.2.5p9,它描述foo<Args...>如何匹配foo<int, double>

template <typename T, typename U>
struct foo {};


struct converter
{
 template <template <typename...> class Bar, class ...Args>
     converter(const Bar<Args...> &){}
};

int main()
{
    converter c1((foo<int,double>())); // This works.
    converter c2 = foo<int,double>();// This works
}

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

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