【发布时间】:2020-07-17 22:48:57
【问题描述】:
有没有一种好方法来评估是否存在多个参数的显式构造函数?这与question 非常相似,除了std::is_convertible 不适用于这种情况,因为我们有多个参数传递给我们正在测试的构造函数。
例如:
#include <iostream>
#include <type_traits>
struct InitParams
{
int Parameter1;
int Parameter2;
};
class ExampleFloatConstructible
{
public:
explicit ExampleFloatConstructible(float InValue, const InitParams& InParams);
};
class ExampleIntConstructible
{
public:
explicit ExampleIntConstructible(int InValue, const InitParams& InParams);
};
template<typename ClassToTest, typename ArgType>
struct IsExplicitlyConstructibleWithSettings
{
static constexpr bool value = std::is_constructible<ClassToTest, ArgType, const InitParams&>::value;
};
int main()
{
// "Correct" values:
// will be true:
std::cout << "ExampleFloatConstructible Can Be Built from float? " <<
IsExplicitlyConstructibleWithSettings<ExampleFloatConstructible, float>::value << std::endl;
// will be true:
std::cout << "ExampleIntConstructible Can Be Built from int? " <<
IsExplicitlyConstructibleWithSettings<ExampleIntConstructible, int>::value << std::endl;
// "Incorrect" values:
// will also be true, because int is convertible from float
std::cout << "ExampleIntConstructible Can Be Built from float? " <<
IsExplicitlyConstructibleWithSettings<ExampleIntConstructible, float>::value << std::endl;
// will also be true, because float is convertible from int
std::cout << "ExampleFloatConstructible Can Be Built from int? " <<
IsExplicitlyConstructibleWithSettings<ExampleFloatConstructible, int>::value << std::endl;
}
【问题讨论】:
-
is_convertible将如何处理多个参数? -
@CleitonSantoiaSilva,这就是问题的重点。
-
好吧,如果你的调用有多个参数,那么你甚至不需要问“is_convertible”对吗?
-
@CleitonSantoiaSilva,如果你不做那一半,你会考虑隐式+显式转换。发帖人希望在测试中禁止隐式转换。
-
@CleitonSantoiaSilva is_convertible 刚刚提到了另一个问题,该问题能够使用 is_convertible 来测试具有一个参数的构造函数是否存在显式构造函数:stackoverflow.com/questions/42786565/…
标签: c++ templates c++17 sfinae