简体   繁体   English

我如何为std :: string专门化这个类模板?

[英]How do i specialize this class template for std::string?

I am writing a TMP to count the number of elements passed to a struct as template parameters using variadic templates. 我正在编写一个TMP来使用可变参数模板计算传递给struct的元素数量作为模板参数。 This is my code: 这是我的代码:

template<class T, T... t>
struct count;

template<class T, T h, T... t> 
struct count<T, h, t...>{
 static const int value = 1 + count<T, t...>::value;
};

template<class T>
struct count<T>{
 static const int value = 0;
};

template<>
struct count<std::string, std::string h, std::string... l>{
 static const int value = 1 + count<std::string, l...>::value;
};

template<>
struct count<std::string>{
 static const int value = 0;
};

int main(){
 std::cout << count<int, 10,22,33,44,56>::value << '\n';
 std::cout << count<bool, true, false>::value << '\n';
 std::cout << count<std::string, "some">::value << '\n';
 return 0;

} }

I get an error on the third instantiation of count with std::string because g++ 4.7 tells me error: 'class std::basic_string<char>' is not a valid type for a template non-type parameter . 我在使用std::string count第三个实例时出错,因为g++ 4.7告诉我error: 'class std::basic_string<char>' is not a valid type for a template non-type parameter Any workaround for this? 有什么解决方法吗?

The problem is not the type std::string but the literal "some" in your call 问题不是std::string类型,而是调用中的文字"some"

std::cout << count<std::string, "some">::value << '\n';

Unfortunately, it is not possible to pass a string or floating point literal to a template as is also written in this answer or in that one . 不幸的是,不可能将字符串或浮点文字传递给模板,这也是在这个答案中在那个 答案 写的。

Sorry to disappoint you, but there's no way around this. 很抱歉让你失望,但没有办法解决这个问题。 Non-type template parameters can only be primitive types such as: 非类型模板参数只能是原始类型,例如:

  • integral or enumeration 积分或枚举
  • pointer to object or pointer to function 指向对象的指针或指向函数的指针
  • reference to object or reference to function 引用对象或引用函数
  • pointer to member 指向成员的指针

std::string or other types simply don't work there. std::string或其他类型根本不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM