Specialize a void function template to a const cha

2019-03-04 18:19发布

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.

2条回答
贼婆χ
2楼-- · 2019-03-04 18:32

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.

#include <typeinfo>
#include <iostream>

namespace detail {

  template <typename T> struct foo_helper {
    static std::string helper() {
      return typeid(T).name();
    }
  };

  template <int N> struct foo_helper<const char [N]> {
    static std::string helper() {
      return "Const Char Array";
    }
  };
}

template <typename T> std::string foo(T& obj) {
  return detail::foo_helper<T>::helper();
}

int main() {
  std::string x;
  const char c[] = "hard coded";
  std::cout << foo(x) << std::endl;
  std::cout << foo(c) << std::endl;
}

This calls the specialization properly for the constant string. I also changed T obj into T& 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.htm

查看更多
相关推荐>>
3楼-- · 2019-03-04 18:33

You 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.

查看更多
登录 后发表回答