gpt4 book ai didi

c++ - 为什么此 C++ 代码中的构造函数不明确,我该如何解决?

转载 作者:可可西里 更新时间:2023-11-01 16:13:47 26 4
gpt4 key购买 nike

在下面的代码中,编译器无法确定我要使用哪个构造函数。为什么,我该如何解决这个问题? ( Live example )

#include <tuple>
#include <functional>
#include <iostream>

template<typename data_type, typename eval_type, typename Type1, typename Type2>
class A
{
public:
using a_type = std::tuple<Type1, Type2>;
using b_type = std::tuple<std::size_t,std::size_t>;

inline explicit constexpr A(const std::function<data_type(a_type)>& Initializer,
const std::function<eval_type(data_type)>& Evaluator,
const Type1& elem1, const Type2& elem2)
{
std::cout << "idx_type" << std::endl;
}
inline explicit constexpr A(const std::function<data_type(b_type)>& Initializer,
const std::function<eval_type(data_type)>& Evaluator,
const Type1& elem1, const Type2& elem2)
{
std::cout << "point_type" << std::endl;
}
};

int main()
{
int a = 1;
long long b = 2;
auto c = A<double, double, long long, int>{
[](std::tuple<long long,int> p)->double { return 1.0*std::get<0>(p) / std::get<1>(p); },
[](double d)->double { return d; }, b,a
};

return 0;
}

最佳答案

它不起作用的原因是因为 lambda 不是 std::function因此编译器尝试使用 the fifth 创建一个构造函数的重载。问题是你的 A由于这种转换和 std::tuple<long long,int> 的原因,可以使用构造函数和 std::tuple<std::size_t,std::size_t>可以相互构造,这使得编译器难以选择要选择的构造函数。

您可以做的是显式转换为所需的 std::function (注释中使用@PasserBy 的 MCVE),like this :

#include <tuple>
#include <functional>
#include <iostream>

template<typename data_type, typename Type1, typename Type2>
class A
{
public:
using a_type = std::tuple<Type1, Type2>;
using b_type = std::tuple<std::size_t,std::size_t>;

A(const std::function<data_type(a_type)>&)
{
std::cout << "idx_type" << std::endl;
}
A(const std::function<data_type(b_type)>&)
{
std::cout << "point_type" << std::endl;
}
};

int main()
{
std::function<double(std::tuple<long long, int>)> func = [](auto p) -> double { return 1; };
auto c = A<double, long long, int>{
func
};
}

关于c++ - 为什么此 C++ 代码中的构造函数不明确,我该如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49280668/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com