我如何static_assert容器的底层元素?

时间:2013-10-15 05:05:43

标签: c++

template <typename T>
MyFun(const T container)
{
    // I want to static_assert that all elements in T are equal to SomeType
}

我该怎么做?我正在考虑static_assert(std::is_same<T::type,SomeType>)的问题,但这当然不起作用......

3 个答案:

答案 0 :(得分:2)

你可以使用

 static_assert(std::is_same<typename T::value_type,SomeType>::value, "type in the container is different");

答案 1 :(得分:1)

如果是标准容器......

template <typename Container>
MyFun(const Constainer& container)
{
    static_assert(std::is_same<typename Container::value_type, SomeType>::value)
    // I want to static_assert that all elements in Container are equal to SomeType
}

答案 2 :(得分:1)

你需要像

这样的东西
static_assert(std::is_same<typename T::value_type, SomeType>::value, 
              "It does not work");

确定定义的value_type容器类型是它所拥有的元素的类型(就像标准库容器一样)。

请参阅std::is_samestatic_assert