【问题标题】:copying constness in templates fails strangely based on type在模板中复制 constness 根据类型奇怪地失败了
【发布时间】:2016-03-20 02:06:50
【问题描述】:

我编写了一个模板来复制 C++11 的指针参数的常量:

template<typename S, typename D>
struct copy_const {
    typedef typename std::conditional<std::is_const<S>::value,
          typename std::add_const<D>::type,
          typename std::remove_const<D>::type>::type type;
};

在这样的方法中使用:

template<typename T, typename U,
    class=typename std::enable_if<std::is_convertible<T, char>::value>::type>
typename copy_const<T, U>::type pointer(T*, U);

根据 U 的类型,我得到不同的行为:

static_assert(std::is_same<decltype(pointer((char *)0, 0)), int>::value,
              "bad pointer 1");
static_assert(std::is_same<decltype(pointer((const char *)0, 0)), const int>::value,
              "bad pointer 2");
static_assert(std::is_same<decltype(pointer((const char *)0, 0)), int>::value,
              "bad pointer 3");

error: static_assert failed "bad pointer 2"

基本上,无论 T 的常量如何,我都会得到“int”返回值,即使我已验证 T 已解析为 const char。

现在,如果我将 U 更改为其他类,则常量被正确复制:

struct V{};
static_assert(std::is_same<decltype(pointer((char *)0, V())), V>::value,
              "bad pointer 4");
static_assert(std::is_same<decltype(pointer((const char *)0, V())), const V>::value,
              "bad pointer 5");
static_assert(std::is_same<decltype(pointer((const char *)0, V())), V>::value,
              "bad pointer 6");

error: static_assert failed "bad pointer 6"

即使以下用于复制 const 的断言成功:

static_assert(std::is_same<decltype(0), int>::value, "bad type");
static_assert(std::is_same<std::add_const<int>::type, const int>::value,
              "bad const 1");
static_assert(std::is_same<const int, copy_const<const int, int>::type>::value,
              "bad const 2");

这是编译器错误,还是我忽略了什么?

【问题讨论】:

    标签: c++ templates c++11 stl


    【解决方案1】:

    在函数的返回类型上忽略标量类型的 const 限定符。例如:

    static const int returns_const_int();
    
    int main()
    {
        static_assert(
            std::is_same<decltype(returns_const_int()), const int>::value,
            "not const"
        );
    }
    

    原因

    warning: type qualifiers ignored on function return type
        [-Wignored-qualifiers]
    static const int returns_const_int();
    
    static assertion failed: not const
    

    所以在pointer() 被声明返回const int 的情况下,它实际上是返回一个非常量int。

    但是,对于类类型,情况相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-13
      • 1970-01-01
      • 2011-04-08
      • 1970-01-01
      • 2014-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多