bre*_*att 4 c++ templates template-specialization c++11
我有一个类,它包含一些静态大小的容器:
template <typename Container>
struct Point {
Container container;
...
void bar();
}
Run Code Online (Sandbox Code Playgroud)
其中一Container类可能是这样的:
struct Container1 {
static constexpr size_t size = 5;
}
Run Code Online (Sandbox Code Playgroud)
现在我想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>(); }
};
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
顺便说一句,你的问题闻起来就像一个XY问题:你真的需要专门bar()研究Container::size吗?在以下示例中,将针对任何大小展开循环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 &&) {}
};
Run Code Online (Sandbox Code Playgroud)