2
votes

I have a template member function of a class that I'm using for adding various different types to a list, with special handling and wrapping (everything ends up wrapped in a var object) for specific types:

template<typename V> const var& addvar(const V& v);

template<> const var& addvar<std::string>(const std::string& v) {/*stuff*/}

However, I'm passing around strings (well, const char arrays) like this to it:

object.addvar("lol");

Although I'm handling everything as std::strings, this pops in as some sort of const char array reference in the template parameter type deduction. So I get an error about not having a function for it, even with the above std::string specialization. I'm familiar with template array size deduction, so I'm trying to use that format to create an addvar that can handle such a thing, something like:

template<size_t N> const var& addvar<char>(const char& (&v)[N]) {/*stuff*/}

But things are going horribly with compiler errors about illegal arrays of references. This is in VC++ 2010, if there's any specific weirdness with that, but I get the feeling I'm messing up something fundamental here.

3

3 Answers

4
votes

You can't partially specialize template function, so it has to be an overload (= a template that doesn't share anything with the initial addvar template function):

template<size_t N> const var& addvar(const char (&v)[N]) {/*stuff*/}
1
votes
template<size_t N> const var& addvar<char>(const char& (&v)[N]) {/*stuff*/}
                                                     ^

Delete & after const char, you are trying to specialize for array of references that way, which is not what you want (and is illegal either way).

1
votes

The function would look like this:

template <std::size_t N>
void foo(const char (&a)[N])

But your problem is that you cannot partially specialize a function. What however you can do, is defining a simple overload, which will be preferred and called from the compiler.