I am starting with variadic templates in C++11 and I wonder if its possible to create a struct / class method that gets its name from a template parameter
Something like:
MySmartTemplate<"foo", int, "bar", double> MyStruct;
// which should result in:
struct MyStruct
{
void foo(int val){...}
void bar(double val){...}
};
where the template parameters possibly come pairwise as <name> + <type>
Thanks
This is not possible with templates at all. A template in c++ is parametrized by a list of one or more template parameters. Each of them may be either:
Now, to be able to (theoretically) construct something like void foo(int val){...}
, you need to pass the name of "foo" and it's parameter type into our imaginary template. While passing the type of val
is not a problem, passing "foo"s name is impossible. The only non-type template parameters that you can use are:
You should also note that the non-type template parameters of reference and pointer types have a few exceptions, namely they can not refer to or be an address of a string literal (related: this question). Considering the above, there is no way to pass a string literal to a template, and thus it is impossible to achieve what you want with templates.
On a side note, while variadic templates are a nice addition to the language, they have a few limitations, namely you can only perform the expansion of the parameter pack, but you can't address individual parameters in the pack.
So, to conclude, no, what you want is not possible with templates.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments