如何将这个类模板专门用于std::string

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

本文关键字:用于 std string      更新时间:2023-10-16

我正在编写一个TMP,以使用可变模板计算作为模板参数传递给struct的元素数量。这是我的代码:

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;

}

我在countstd::string的第三次实例化中得到一个错误,因为g++ 4.7告诉我error: ‘class std::basic_string<char>’ is not a valid type for a template non-type parameter。有什么解决办法吗?

问题不在于类型std::string,而在于调用中的文字"some"

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

不幸的是,不可能像这个答案或那个答案中所写的那样,将字符串或浮点文字传递给模板。

很抱歉让你失望,但这是没有办法的。非类型模板参数只能是基元类型,例如:

  • 积分或枚举
  • 指向对象的指针或指向函数的指针
  • 对对象的引用或对函数的引用
  • 指向成员的指针

std::string或其他类型在那里根本不起作用。