c++ - 将对象传递给函数时,如何防止模板化构造函数将类作为参数

标签 c++ templates constructor c++17

我有一个类,它有一个初始化数组的模板化构造函数,但是当
我将初始化的对象传递给一个函数,该函数使用模板化构造函数进行复制(这就是我的想法)。

是否有正确的语法/方法可以防止这种情况发生?

我的代码定义了类、函数和主 run code :

#include <stdio.h>
#include <array>

template<typename T, typename Args>
class myClass{

public:
    std::array<T, 10> data;

    template<typename ... Element>
    constexpr myClass(Element&&... input) : data{input...} {};

    myClass(const myClass& obj){
        data = obj.data;
    }
};

template<typename T, typename Args>
constexpr auto myFunction(myClass<T, Args> obj){
    return 0;
}

template<typename T, typename Args>
constexpr auto myFunction(myClass<T, Args>&& obj){
    return 0;
}

int main()
{
    myClass<double, std::tuple<int, int, double>> expr_obj;

    auto temp = expr_obj;//ERROR

    auto result = myFunction(expr_obj); //ERROR

    return 0;
}

错误消息如下所示:
main.cpp: In instantiation of ‘constexpr myClass<T, Args>::myClass(Element&& ...) [with Element = {myClass<double, std::tuple<int, int, double> >&}; T = double; Args = std::tuple<int, int, double>]’:
<span class="error_line" onclick="ide.gotoLine('main.cpp',43)">main.cpp:43:38</span>:   required from here
main.cpp:19:58: error: cannot convert ‘myClass >’ to ‘double’ in initialization
     constexpr myClass(Element&&... input) : data{input...} {};
                                                          ^

我添加了来自 CLion 的错误消息,因为它提供了更多信息:
In instantiation of ‘constexpr myClass<T, Args>::myClass(Element&& ...) [with Element = {myClass<double, std::tuple<int, int, double> >&}; T = double; Args = std::tuple<int, int, double>]’:

cannot convert ‘myClass<double, std::tuple<int, int, double> >’ to ‘double’ in initialization
  304 |     constexpr myClass(Element&&... input) : data{input...} {};

最佳答案

一种方法是约束 Element 的元素。类型为 T .那看起来像

template<typename T, typename Args>
class myClass{

public:
    std::array<T, 10> data;

    template<typename ... Element, std::enable_if_t<(std::is_same_v<std::decay_t<Element>, T> && ...), bool> = true>
    //                             ^  this says only enable this template if all Element are T                ^
    constexpr myClass(Element&&... input) : data{input...} {};

    myClass(const myClass& obj){
        data = obj.data;
    }
};

关于c++ - 将对象传递给函数时,如何防止模板化构造函数将类作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60670040/

相关文章:

c++ - 从 stdio 读取两个文件

c# - float 问题 : C++ to C# migration

templates - Go HTML 模板中的自动资源修订文件名

c++ - 从 C++11 模板参数包创建空指针

c++ - 这是未定义的行为还是误报警告?

c++ - "Segmentation fault"在linux上实现intel MKL的DFT

c++ - 将指针传递给函数 C++

.net - 测试 Wpf Control 实例化性能

java - 对象是否应该知道它需要哪个 'arguments'

javascript - 在 1 行代码中自定义构造函数