Re: Arity in C++0x Variadic Class Method
On 8 Mrz., 02:33, PGK <graham.k...@gmail.com> wrote:
I'd like to define a method which takes twice (say) the number of
template parameters which define the class. The following class
attempts to use explicit recursion for this, but fails. Does anyone
know if this is possible?
template <typename Type, typename ... Types>
struct Foo {
void bar(Type t1, Type t2) { std::cout << t1 << " " << t2 <<
std::endl; }
void bar(Type t1, Type t2, Types ... ts) {
std::cout << t1 << " " << t2 << std::endl;
bar(ts...);
}
};
It should be possible, but not as you tried. The reason of failure
is simple due to the fact that once Foo has been instantiated
you have selected a variadic of given sice. To fix this, just
make bar a function template that is constrained regarding
the number of arguments. Your can also add type-matching
requirements via sfinae combinaed with std::is_same or
std::is_convertible, but I omitted that in the following:
template <typename Type, typename ... Types>
struct Foo {
void bar(Type t1, Type t2) { std::cout << t1 << " " << t2 <<
std::endl; }
template<typename... U,
typename = typename std::enable_if<sizeof...(U) == 2*sizeof...
(Types)>::type>
void bar(Type t1, Type t2, U... ts) {
std::cout << t1 << " " << t2 << std::endl;
bar(ts...);
}
};
Whether this works, depends on your Type/Types
combinations. Then pack expansion inside bar
will try to match the first two members of ts
with Type, so this will only work, if each Ui in U
satisfies the constraint std::is_same<Ui, Type>
or std::is_convertible<Ui, Type>.
You can add this as one sfinae blocker in the
dummy type added to bar's template parameter
list.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]