【问题标题】:Checking if a class has a copy constructor with TMP检查一个类是否有带有 TMP 的复制构造函数
【发布时间】:2013-03-25 22:39:13
【问题描述】:

我一直在尝试使用一点 SFINAE 来确定泛型类型 T 是否具有我可以使用的复制构造函数。这是我目前所在的位置。

template <bool statement, typename out>
struct Failable
{
    typedef out Type;
};
//This class is only used to insert statements that 
//could encounter substitution failure


template <typename O>
struct COPY
{
    template <typename T>
    typename Failable<true == sizeof(&T::T(const T&)), char>::Type copy(int)
    {}

    template <typename T>
    typename Failable<true, int>::Type copy(...)
    {}

};

但是,这也是我有点卡住的地方。 &amp;T::T(const T&amp;) 显然是一个无效的语句,因为我们不能提供带有指向成员的指针的参数列表,即使是 p-t-m-function。 我总是可以尝试指定某种void (T::*ptmf)(const T&amp;) = &amp;T::T,并希望它隐式地确定正确的重载构造函数以放入指向成员函数的指针中,但这也意味着构造函数具有特定的返回类型,我必须指定它。

还有其他人有什么想法可以让我继续前进吗? (我还需要应用类似的概念来检查赋值运算符。)

提前致谢。

【问题讨论】:

    标签: c++ template-meta-programming sfinae pointer-to-member


    【解决方案1】:

    您可以为此使用std::is_copy_constructiblestd::is_assignable

    【讨论】:

    • ...为什么一个可能很困难的问题只需要有简单的答案? sigh 感谢您让我知道这件事!不过,我希望看看是否有办法手动实现它=)
    • @Serge:您可能会查看stackoverflow.com/questions/2733377/… - 将测试更改为sizeof U(*(U*)0)) 之类的东西(注意U(U()) 也需要默认可构造性,所以不好)。
    【解决方案2】:

    你可以用你的代码做,只需要稍微修改一下。

    template <bool statement, typename out>
    struct Failable
    {
         typedef out Type;
    }; 
    
    template <typename O>
    struct COPY
    {
    
         static O MakeO();
    
         template <typename U> // U and T are the same type
         static typename Failable<(sizeof U(MakeO())), char>::Type copy(int);
    
         template <typename U>
         static typename Failable<true, int>::Type copy(...);
    
         enum { value = sizeof(char) == sizeof( copy<O>(0) ) };
    };
    

    【讨论】:

    • 我尝试使用此解决方案,因为我需要使用旧的 g++。如果复制 ctor 是私有的,则会显示错误消息 `error: 'CA::CA(const CA&)' is private。可以避免吗?不然怎么可能没有copy ctor呢?
    • 实际上它确实适用于 g++ 4.7+。起初我尝试使用 4.1.2 但失败了。谢了!
    • // U and T are the same type T 在哪里?你的意思是O
    • COPY<:stringstream>::value 将为 1,但 std::stringstream 没有复制 ctor。我认为这个模板类是正确的,它是 STL 的一个奇怪的特性。为什么 COPY<:stringstream>::value == 1?
    猜你喜欢
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2021-06-30
    • 2021-03-22
    • 2015-09-08
    相关资源
    最近更新 更多