mercredi 4 mars 2015

Specify integral template argument of constructor template inside a class template

I am creating a std::tuple equivalent for a union (instead of a struct). To do so, I also added a constructor template, where the first template argument is size_t idx, to initize the idxth element of the union. Moreover, there is another variadic template to specify what the argments of the actual type constructor are.


Unfortunately, I can't seem to specify the idx template argument when calling the constructor, and it is also not implied (as it is not part of the argument list). Is there any way around this? How can I specify a size_t contructor template argument?


Example code:



#include <iostream>

template<typename T>
struct Foo
{
T d_val;
size_t d_other_val;
template<size_t idx>
Foo(T val)
{
d_val = val;
d_other_val = idx;
}
};


int main() {
Foo<double> f = Foo<4>(2.6);

std::cout << f.d_val << " " << f.d_other_val << '\n';
}


Source: http://ift.tt/1DLQd1c


Of course, the 4 is matched on the class template, and not the constructor template. Is this fixable? Note that idx should be a compile time thing, and not a normal constructor argument. Although in this example, that would be the trivial solution.


PS: the problem of course is, that in general constructor templates are implied by the arguments with which the constructor is called. Implicit specification is to the best of my knowledge not possible for the idx template argument.


Aucun commentaire:

Enregistrer un commentaire