问题描述
是否可以使用编译时常量有条件地隐藏或禁用模板类中的函数?
Is it possible to conditionally hide or disable functions in a template class using compile time constants?
想象一下下面的类:
template<size_t M, size_t N>
class MyClassT
{
// I only want this function available if M == N, otherwise it is illegal to call
static MyClassT<M, N> SomeFunc()
{
...
}
}
MyClassT<2,2>::SomeFunc(); // Fine
MyClassT<3,2>::SomeFunc(); // Shouldn't even compile
推荐答案
使用偏特化和继承:
// Factor common code in a base class
template <size_t n, size_t m>
class MyClassTBase
{
// Put here the methods which must appear
// in MyClassT independantly of n, m
};
// General case: no extra methods
template <size_t n, size_t m>
class MyClassT : MyClassTBase<n, m>
{};
// Special case: one extra method (you can add more here)
template <size_t n>
class MyClassT<n, n> : MyClassTBase<n, n>
{
static MyClassT<n, n> SomeFunc()
{
...
}
};
另一种选择是使用 SFINAE:std::enable_if
或其变体:
Another option is to use SFINAE: std::enable_if
or a variant thereof:
template <size_t n, size_t m>
class MyClassT
{
template <typename EnableIf = char>
static MyClassT<n, m> SomeFunc(EnableIf (*)[n == m] = 0)
{
...
}
};
更详细的替代方案(但如果您不了解 SFINAE 和指向数组的指针,则不那么令人惊讶)
the more verbose alternative (but less surprising if you don't know about SFINAE and pointer to arrays) being
template <size_t n, size_t m>
class MyClassT
{
template <typename Dummy = char>
static MyClassT<n, m>
SomeFunc(typename std::enable_if<n == m, Dummy>::type * = 0)
{
...
}
};
通常,我更喜欢 SFINAE 方法,其中有一个或两个成员函数可以启用或禁用.一旦它变得比这更复杂,我就更喜欢偏特化技术.
Generally, I prefer SFINAE approaches where there is one or two member functions to enable or disable. As soon as it gets more complex than this, I prefer the partial specialization technique.
SFINAE 代码是错误的,因为没有模板函数.已更正.
The SFINAE code was wrong, since there were not template functions. Corrected.
这篇关于基于编译时常量禁用/隐藏模板中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!