简体   繁体   中英

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:

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. 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 doesn't support C++0x variadic templates to the fullest yet (and to be fair, the specification is still constantly changing in details).

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> .

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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