c++ - 根据类模板参数淘汰类模板构造函数

标签 c++ templates c++11

给定以下类模板:

#include <type_traits>

template< class T, class Unrelated >
struct MyClass
{
    static_assert( std::is_same< T, char >::value ||
                   std::is_same< T, char16_t>::value ||
                   std::is_same< T, char32_t >::value,
                   "MyClass only defined for char, char16_t, char32_t" );
    MyClass( T init ) {}
    MyClass( char32_t init ) {}
    // ...
};

第二个 ( char32_t ) 构造函数是 T == char 的特例。和T == char16_t .

显然,它会生成 T == char32_t 的错误。 。因此,我想针对这种情况“淘汰”该构造函数。该类相当大,大部分代码是为所有人共享的 T ,所以我不想让整个类(class)专门针对char32_t案例。

我见过 enable_if 以及相关答案,如 this one在这里,但无法将任何提供的解决方案/示例适应我的具体情况(类模板中的非模板化构造函数)。

所以我请求您的帮助:

如何禁用MyClass( char32_t ) MyClass< T, U > 的构造函数与 T == char32_t

或者,如果更容易的话,如何禁用 MyClass( T init ) T == char32_t 的构造函数? (对于 char32_t ,两个构造函数在功能上是相同的。)

最佳答案

I have seen enable_if as well as related answers like this one here on SO, but was unable to adapt any of the presented solutions / examples to my specific case (non-templated constructor in class template).

您必须使用默认参数使构造函数模板化。然后确保 enable_if 取决于默认参数。不久:

//void_t trick made a type dependant
template<class T, class ... >
struct always
{
    typedef T type;
};

template<class T, class ... D>
using always_t = typename always<T, D...>::type;

template<class T, class Unreleated>
class MyClass
{
public:
    // ... 
    MyClass( T init ) 
    {
    }

    template<class U = void>
    MyClass( std::enable_if_t<
                !std::is_same<T, char32_t>::value,
                always_t<char32_t, U> //< enable_if expression depends on U
             > init)
   {
      //decltype(init) is always char32_t, but the compiler can not know that
   }
};

尝试一下 live .

关于c++ - 根据类模板参数淘汰类模板构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35102498/

相关文章:

c++ - 模板变量 `list` 不起作用?

c++ - bool 自动转换为 nullptr_t

c++ - 用 c++11 等价物替换 boost::thread 和 boost::mutex 是否明智?

c++ - libxml/解析器.h : in c++ ubuntu

c++ - 我正在尝试创建一个类 vector ,然后用 for 循环命名每个类

c++ - 获取准确的窗口区域大小 - CreateWindow 窗口大小不是正确的窗口大小

c++ - 在 C++ 中继承结构的最有效方法?

android - 如何使用现有的 android 项目作为其他 android 项目的库/源?

c++ - 如何使我的 C++ 类事件系统成为限于类型数组的模板类?

c++ - 如果仅使用模板,则启用模板功能