gpt4 book ai didi

c++ - std::is_assignable 和 const 指针对象

转载 作者:行者123 更新时间:2023-11-30 02:39:19 26 4
gpt4 key购买 nike

我在尝试使用 std::is_assignable 进行推断时遇到了一个小问题

我的代码:

#include <string>
#include <type_traits>

class Object{};

enum my_conv {
string, const_object, object
};

template<typename T, typename V = void>
struct deducer;

template<typename T>
struct deducer<T, typename std::enable_if< std::is_constructible<std::string, T>::value >::type > {
static const my_conv value = my_conv::string;
}; // (1) test for string

template<typename T>
struct deducer<T, typename std::enable_if< std::is_assignable<Object*&, T>::value >::type > {
static const my_conv value = my_conv::object;
}; // (2) test for Object derived

template<typename T>
struct deducer<const T, typename std::enable_if< std::is_assignable<Object*&, T>::value >::type > {
static const my_conv value = my_conv::const_object;
}; // (3) should test for const Object derived

class Test : public Object {
public:
Test() = default;
};

int main() {
std::string str;
Test* t = new Test;
const Test* tconst = static_cast<const Test*>(t);

deducer<decltype(t)>::value;// deduce as (1)
deducer<decltype(str)>::value;//deduce as (2)
deducer<decltype(tconst)>::value;//fail to deduce as (3)... why?
}

而且我真的不明白为什么编译器无法实例化第三个推导器....

编辑:

测试时我看到这样写:

struct deducer<const T*, typename std::enable_if< std::is_assignable<Object*&, T*>::value >::type >

让它工作,但我想我仍然需要一些解释......因为我仍然不明白第一时间出了什么问题......

最佳答案

显然它不会匹配 (1) 因为 const Test * 不能从 std::string 构造。

它不会匹配 (2),因为指向 const 的指针不可分配给非常量指针。

它不会匹配 (3),因为它适用于常量类型,而不是指向常量类型的指针。

请记住,如果 T 是像 Test* 这样的指针类型,那么 const T 就是一个常量指针 Test * const ,不是指向常量的指针 Test const *

关于c++ - std::is_assignable 和 const 指针对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29894610/

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