【问题标题】:Is there a way to detect construction of a const qualified object? [duplicate]有没有办法检测 const 限定对象的构造? [复制]
【发布时间】:2014-04-12 14:45:04
【问题描述】:

假设有两个声明:

const type x;  // case a
type y;        // case b

是否可以在type 的构造函数中检测大小写“a”或“b”,以便执行不同的操作?

根据标准 §12.1/3 我们有:

可以为 const、volatile 或 const volatile 对象调用构造函数。 const 和 volatile 语义 (7.1.6.1) 不适用于正在构建的对象。它们在最派生对象 (1.8) 的构造函数结束时生效。

因此this behaves like expected 在构造时永远不会被const 限定(否则你怎么能编辑正文中的成员对象?)。因此,似乎不可能在 this 上使用类型特征。

对此的用例如下:假设您正在使用描述特定对象(在更广泛的意义上)的底层 C API,采用提示关于它们未来的用途:

  • STATIC = 不会被修改
  • DYNAMIC = 可以修改

可以围绕这些 C 对象创建一个包装器,并在 const 构造上给出 STATIC 提示,在非 const 构造上给出 DYNAMIC 提示。当然 const_cast 存在并且可能会搞砸,但我假设 sane 在这里编码:P.

我是否遗漏了什么(同时考虑 C++11 和 C++14)?

【问题讨论】:

  • 想象这是可能的,我会定义const T make();,然后说T nonconst = make();。繁荣?
  • @KerrekSB,好吧,nonconst 的复制构造函数会检测到它的非 constness 并读取另一个对象的提示(来自 make)并构造一个 DYNAMICally 提示对象?
  • 好吧,如果有的话,复制一些东西然后得到不同的东西真的很奇怪和意想不到......我想你很难争辩说这样的事情应该是可能的。
  • @KerrekSB,为什么?您唯一应该想到的是:我正在考虑的对象是const?不?然后它会被STATICally 提示。是的?然后它会被DYNAMICally 提示。此外,这个 hints 将是实现细节,而不是接口的一部分,因此用户无论如何都不应该担心它们。

标签: c++ c++11 constructor constants c++14


【解决方案1】:

我真的不知道它是否值得努力,而且这个解决方案肯定不完美,因为我们必须使用帮助器类 Object<T>,但至少它与您要求的行为非常相似:

#include <iostream>
#include <type_traits>

template<typename T>
using Object = typename std::conditional<std::is_const<T>::value, typename T::const_type, typename T::type>::type;

template<bool IsConst>
struct FooHelper;

struct Foo
{
    typedef FooHelper<false> type;
    typedef const FooHelper<true> const_type;

protected:

    Foo(bool isConst)
    {
        if (isConst)
            std::cout << "const" << std::endl;
        else
            std::cout << "non-const" << std::endl;
    }

};

template<>
struct FooHelper<false> : public Foo
{
    FooHelper() : Foo(false) {}
};

template<>
struct FooHelper<true> : public Foo
{
    FooHelper() : Foo(true) {}
};

int main()
{
    Object<Foo> obj;
    Object<const Foo> cobj;
}

【讨论】:

    猜你喜欢
    • 2010-11-20
    • 2015-10-11
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    相关资源
    最近更新 更多