如何将这个类模板专门用于std::string
How do i specialize this class template for std::string?
我正在编写一个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;
}
我在count
与std::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
或其他类型在那里根本不起作用。
相关文章:
- 专用于 std 元组的模板,而无需用户执行remove_cvref
- 使用 std::应用于 std::bind
- 运算符 += 应用于 std::valarray<int*>
- 为什么这个分配器不适用于"std::allocate_shared"?奇怪的模板替换错误
- 隐式转换为比较函数对象(函子)用于 std::sort 而不是 std::map?
- C++11 基于范围的 for 循环,用于 std::list
- 函数可以应用于 std::optional,并返回一个可选值吗?
- 为什么基于 int 的访问不适用于 std::get(std::tuple)?
- Hana BOOST _Hana_DEFINE_STRUCT不适用于std::unique_ptr
- 模板推导不适用于 std::endl?
- 结构化绑定是否适用于 std::vector?
- 没有适用于 std::unique_ptr 的适当默认构造函数
- 适用于 std::unique_ptr 的内存高效自定义删除器?
- 如何为专用于 std::enable_if 的类定义类外函数
- C++类运算符重载不适用于 std::sort
- 我可以将Brad-Init-list用于STD ::变体的向量吗?
- 为什么不区分大小写适用于 std::unordered_set的 std::hash 函数?
- 用于 std::generate_n 的并行执行可变 lambda 生成器
- 为什么 lambda 函数不适用于 std::min_element?
- 如何将 lambda 用于 std::find_if