如何专门化const和非const容器的模板

How to specialize a template for const and non const containers?

本文关键字:const 和非 专门化      更新时间:2023-10-16

我试图使模板的2专业化:

  • 接受非const容器
  • 另一个接受const容器

我的当前代码是:

template<class T>
struct A{
    constexpr static int value=0;
};
template<template<typename>class T,typename...Args>
struct A<T<Args...>>{//accept non const containers
    constexpr static int value=1;
};
template<template<typename>class T,typename...Args>
struct A<T<Args...> const>{//accept const containers
    constexpr static int value=2;
};

ideone

但是这段代码不起作用,如果我使用const容器,它使用第一个A的实例化而不是第三个。

using Type=const std::array<int,10>;
std::cout<<A<Type>::value;//output is 0

我试着删除

template<class T>
struct A{
    constexpr static int value=0;
};

但是它给出了很多错误…

我认为你可以做到这一点没有可变的模板参数:

template<class T>
struct A{
    constexpr static int value=0;
};
template<class T>
struct A<T const> {
    constexpr static int value=2;
};

int main()
{
    std::cout << A<const std::vector<int>>::value;
}

你希望模板模板形参有可变的模板参数列表(实际上所有标准容器都有多个模板形参):

template< template<typename...> class T, typename...Args >
//                         ^^^

那么这个代码

#include <vector>
#include <iostream>
template<class T>
struct A{
    constexpr static int value=0;
};
template<template<typename...>class T,typename...Args>
struct A<T<Args...>>{//accept non const containers
    constexpr static int value=1;
};
template<template<typename...>class T,typename...Args>
struct A<T<Args...> const>{//accept const containers
    constexpr static int value=2;
};
int main()
{
    std::cout << A<const std::vector<int>>::value;
}

输出2

但是它仍然不能与std::array一起工作,因为它在其参数列表中包含一个非类型模板参数(并且不能匹配可变类型包)。这恐怕不能用一般的方法解决。

始终使用type_traits。http://en.cppreference.com/w/cpp/types/is_const

#include <type_traits>
#include <iostream>
#include <array>
#include <vector>
int main()
{
   std::cout << std::is_const< const std::vector<int> > ::value << 'n';
   std::cout << std::is_const< std::vector<int> >::value << 'n';
   std::cout << std::is_const< const std::array<int, 4> >::value << 'n';
   std::cout << std::is_const< std::array<int, 4> > ::value << 'n';
}

输出如预期:

1
0
1
0