我有一个我想要专门化的模板化函数foo
to const char[N]
(硬编码字符串)
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]
我以为我可以做一些像已经完成的事情Here http://www.dev102.com/2009/01/12/c-tip-how-to-get-array-length/.
但它效果不佳,因为我没有传递参数,只是传递模板类型。
我可以这样做,但没有理由将参数传递给该函数。
该示例不起作用,因为我没有传递变量。尝试了一些事情,但无法让它发挥作用。
这是我唯一无法解决的专业。我专门为 int、string 和其他类型设计了该函数,它们工作正常。
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)"
第一个模板化声明没有任何有意的代码...我正在尝试获得将用于我的案例的正确专业化。
你必须分两步完成。由于不能部分特化函数,因此必须让函数调用可以部分特化的类。所以下面的方法会起作用。
#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;
}
这正确地调用了常量字符串的特化。我也改变了T obj
into T& obj
,因此 g++ 会将静态字符串作为数组而不是指针传递。有关部分专业化的更多详细信息,请参阅http://www.gotw.ca/publications/mill17.htm http://www.gotw.ca/publications/mill17.htm
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)