c++ - 根据成员容器的大小专门化成员函数

标签 c++ c++11 templates template-specialization

我有一个包含一些静态大小容器的类:

template <typename Container>
struct Point {
    Container container;
    ... 
    void bar();
}

Container 类可能如下所示:

struct Container1 {
    static constexpr size_t size = 5;
}

现在我想根据容器的大小专门化 bar 方法。我不明白该怎么做。

编辑:

我想要一个 C++11 解决方案。 C++14 可能有效,但我们使用的编译器通常对 C++14 的支持参差不齐。

编辑:

Stack Danny 建议使用 Clang 而非 GCC 编译的解决方案。

最佳答案

与其特化,不如使用 SFINAE

template <typename Container>
class Point {
    Container container;
    template<size_t S> std::enable_if_t<S==3>
    bar_t() { std::cout << "specialisation for size=3\n"; }
    template<size_t S> std::enable_if_t<S==5>
    bar_t() { std::cout << "specialisation for size=5\n"; }
    template<size_t S> std::enable_if_t<S==42>
    bar_t() { std::cout << "specialisation for size=42\n"; }
  public:
    void bar()
    { bar_t<Container::size>(); }
};

std::enable_if_t 是 C++14,但您可以自行声明它:

#if __cplusplus < 201402L
template<bool C, typename T=void>
using enable_if_t = typename enable_if<C,T>::type;
#endif

顺便说一句,你的问题闻起来像 XY problem :您真的需要为 Container::size 专门化 bar() 吗?在下面的例子中,一个循环被展开为任意大小的 N

template<typename scalar, size_t N>
class point // a point in R^N
{
    scalar array[N];
  public:
    // multiplication with scalar
    point& operator*=(scalar x) noexcept
    {
        // unroll loop using template meta programming
        loop([array,x](size_t i) { array[i] *= x; };);
        /* alternatively: rely on the compiler to do it
        for(size_t i=0; i!=N; ++i)
            array[i] *= x;
        */
        return *this;   
    }
  private:
    template<size_t I=0, typename Lambda>
    static enable_if_t<(I<N)> loop(Lambda &&lambda)            
    {
        lambda(I);
        loop<I+1>(lambda);
    }
    template<size_t I=0, typename Lambda>
    static enable_if_t<(I>=N)> loop(Lambda &&)         {}
};

关于c++ - 根据成员容器的大小专门化成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54705719/

相关文章:

c++ - std::vector 构造,具有元素的就地构造

c++ - 在字符串 vector 中搜索匹配时出现 std::out_of_range 异常

c++ - 是否有可能有一个非递归的 at_c 实现?

javascript - 下划线模板中的 bool 检查

c++ - 使用 PointCloudLibrary 混淆 segFault 跟踪

c++ - 如何正确传递窗口句柄?

c++ - 我们什么时候在 new (::new) 之前使用作用域解析运算符?

c++ - 队列段错误的复制构造函数

c++ - 如何在 c-ares 中获取 DNS 服务器

所有模板实例的 C++ 单一函数指针