比方说,我有几个不同的课程:
class constructible_from_float {
public:
constructible_from_float(float);
};
class constructible_from_double {
public:
constructible_from_double(double);
};
class constructible_from_long_double {
public:
constructible_from_long_double(long double);
};
然后我想根据它们可构造的类型(简化示例)做一些事情:
#include <type_traits>
template <typename T>
constexpr size_t foo() {
if constexpr (std::is_constructible<T, float>::value) {
return 1;
} else if constexpr (std::is_constructible<T, double>::value) {
return 2;
} else if constexpr (std::is_constructible<T, long double>::value) {
return 3;
} else
return -1;
}
但问题是,所有这些都返回1
:
[[maybe_unused]] auto float_result = foo<constructible_from_float>();
[[maybe_unused]] auto double_result = foo<constructible_from_double>();
[[maybe_unused]] auto long_double_result = foo<constructible_from_long_double>();
我知道这种行为的原因是类型之间的隐式转换。是否有一种合法的(至少可用于三个主要编译器:msvc
和gcc
)clang
的方式来强制编译器区分这些类型。
我不允许更改课程(constructible_from_float
等),但可以做其他所有事情。稳定版本的编译器提供的任何东西都可以(包括c++2a
)。