【问题标题】:SFINAE - enable one function if arguments are copy-constructible and another otherwiseSFINAE - 如果参数是可复制构造的,则启用一个函数,否则启用另一个函数
【发布时间】:2021-01-08 23:59:16
【问题描述】:

如果参数是可复制构造的,我希望调用一个函数和另一个函数(类似于以前的函数,但有额外的代码)。我发现 std::is_copy_constructible 没有按预期工作

#include <iostream>

using namespace std;


struct NoCopy {
    int n;
    NoCopy(const NoCopy&) = delete;
};


template <typename T, 
         typename U, 
         std::enable_if_t<!std::is_copy_constructible_v<U>, int> = 0>
void log_debug(T&& t, U&& u)
{
    
 std::cout<<"\n"<<typeid(U).name()<<" does not have copy constructor; ";  
}
   
   
template <typename T, 
            typename U, 
            std::enable_if_t<std::is_copy_constructible_v<U>, int> = 0>
void log_debug(T&& t, U&& u)
{
    
 std::cout<<"\n"<<typeid(U).name()<<" has copy constructor; ";  
}

int main()
{
    NoCopy a{2};
    log_debug("value is ", a);
    
    std::cout<<"\nstd::is_nothrow_copy_constructible_v  "<<std::is_copy_constructible_v<NoCopy>;  //returns 0 as expected

    return 0;
}


                                                                                                                                                                                                                                    

输出:

6NoCopy 具有复制构造函数;
std::is_copy_constructible_v 0

is_copy_constructible_v 似乎在主函数内部起作用,但在外部不起作用

【问题讨论】:

    标签: c++ templates c++17 copy-constructor


    【解决方案1】:

    问题是这里的U 不是NoCopy,而是NoCopy&amp;

    您可以通过在 enable_if 中使用 std::decay_t&lt;U&gt; 来解决此问题,以去除 cv 限定符并根据需要引用和生成 NoCopy

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-01
      • 2016-09-19
      • 2015-07-02
      • 2012-07-28
      • 1970-01-01
      相关资源
      最近更新 更多