如何防止std :: is_constructible中的隐式转换

问题描述 投票:0回答:1

比方说,我有几个不同的课程:

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>();

enter image description here

我知道,这种行为的原因是类型之间的隐式转换。是否有合法的方法(至少可用于三个主要编译器:msvcgccclang)来强制编译器区分这些类型。

我不允许更改类(constructible_from_float等),但可以做其他所有事情。稳定版本的编译器提供的所有内容都可以(包括c++2a)。

c++ implicit-conversion constexpr typetraits if-constexpr
1个回答
0
投票

[您必须愚弄C ++编译器以向您揭示其要使用的隐式转换,然后使用SFINAE将地毯从其脚下拉出来,并且无法实例化该模板,但无法实例化SFINAE,因此这不是错误。] >

#include <type_traits>
#include <iostream>

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);
};


template<typename T> class convertible_only_to {

public:
    template<typename S, typename=std::enable_if_t<std::is_same_v<T,S>>>
    operator S() const
    {
        return S{};
    }
};


template <typename T>
constexpr int foo() {
    if constexpr (std::is_constructible<T,
              convertible_only_to<float>>::value) {
            return 1;
    } else
    if constexpr (std::is_constructible<T,
              convertible_only_to<double>>::value) {
            return 2;
        } else
    if constexpr (std::is_constructible<T,
              convertible_only_to<long double>>::value) {
            return 3;
    } else
        return -1;
}

struct not_constructible_from_anything {};

int main()
{
    std::cout << foo<constructible_from_float>() << std::endl;
    std::cout << foo<constructible_from_double>() << std::endl;
    std::cout << foo<constructible_from_long_double>() << std::endl;
    std::cout << foo<not_constructible_from_anything>() << std::endl;

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.