简体   繁体   English

基于编译时常量禁用/隐藏模板中的函数

[英]Disabling/Hiding functions in a template based on compile-time constants

Is it possible to conditionally hide or disable functions in a template class using compile time constants? 是否可以使用编译时常量有条件地隐藏或禁用模板类中的函数?

Imagine the following class: 想象一下以下课程:

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

Use partial specialization, and inheritance: 使用部分特化和继承:

// 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()
    {
        ...
    }
};

Another option is to use SFINAE: std::enable_if or a variant thereof: 另一种选择是使用SFINAE: std::enable_if或其变体:

template <size_t n, size_t m>
class MyClassT
{
    template <typename EnableIf = char>
    static MyClassT<n, m> SomeFunc(EnableIf (*)[n == m] = 0)
    {
        ...
    }
};

the more verbose alternative (but less surprising if you don't know about SFINAE and pointer to arrays) being 更冗长的替代方案(但如果您不了解SFINAE和指向数组的指针则不那么令人惊讶)

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)
    {
        ...
    }
};

Generally, I prefer SFINAE approaches where there is one or two member functions to enable or disable. 通常,我更喜欢SFINAE方法,其中有一个或两个成员函数来启用或禁用。 As soon as it gets more complex than this, I prefer the partial specialization technique. 一旦它变得比这更复杂,我更喜欢部分专业化技术。

EDIT: The SFINAE code was wrong, since there were not template functions. 编辑: SFINAE代码错误,因为没有模板功能。 Corrected. 纠正。

The ideal way to provide specializations is to use template specializations. 提供专业化的理想方法是使用模板特化。 You can move all the basic functionality to a base class: 您可以将所有基本功能移动到基类:

template< size_t M, size_t N >
class basic_class{ ... };

template< size_t M, size_t N >
class my_class : basic_class< M, N > { ... };


template< size_t M >
class my_class< M, M > : basic_class< M, N > { ... };

Alternatively, you could add a dummy template parameter and use enable_if : 或者,您可以添加虚拟模板参数并使用enable_if

template< typename Dummy = int >
typename std::enable_if< M == N, my_class >::type some_func( Dummy* = 0 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM