I have a templated function which I want to specialize foo
to const char[N]
(hardcoded strings)
template<typename T>
const std::string foo() ;
template<typename T,int N>
const std::string foo<T[N]>() { return "T[N]"; } //this doesn't work for const char[12]
template<>
const std::string foo<const char*>() { return "Const char"; } //this doesn't work for const char[12]
template<typename T>
void someother function(T obj)
{
string s = foo<T>(); //I want to overload when T is const chat[N]
}
function("Hello World"); //When calling like this the type is const char[12]
I thought I can do something like was done Here.
But it doesn't work as well, because I'm not passing a parameter, just a templated type.
I could do it like that, but there's just no reason to pass a parameter to that function.
The example doesn't work because I'm not passing a variable. Tried a few things, but can't get it to work.
This is the only specialization I'm not able to solve. I've specialized the function for int,string and other types and they work OK.
error LNK2001: unresolved external symbol "class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const __cdecl foo<char const [12]>(void)"
The first templated declaration doesn't have any code in purpose... I'm trying to get the right specialization that will be used for my case.
You have to do it in two steps. Since you can't partially specialize a function, you have to have the function call a class, which can be partially specialized. So the below will work.
This calls the specialization properly for the constant string. I also changed
T obj
intoT& obj
, so g++ would pass the static strings as arrays, not pointers. For more detail on partial specialization, look at http://www.gotw.ca/publications/mill17.htmYou can't. This is impossible. You would need a partial specialization to specialize for
const char(&)[N]
, but since you can't partially specialize functions, then it is impossible. You can always overload for it.