复制构造函数中的“Template typedef”不起作用

时间:2011-03-16 22:29:06

标签: c++ templates metaprogramming smart-pointers copy-constructor

一些背景知识:我正在编写一个基于策略的智能指针(如Loki库中的SmartPtr),它可以具有破坏性的复制语义,如auto_ptr。因此,它需要一个模板拷贝构造函数,它采用非const引用来修改被复制的对象。

我要做的是将复制构造函数所采用的参数的常量参数化为策略中的某个变量,以便在不需要破坏性复制语义时使其成为const。以下是我所提出的想法的简化代码,但遗憾的是,它不起作用,因为编译器无法推断出模板参数。我还有其他技术可用于实现所需的行为吗?

template <typename T, bool isEnabled> struct AddConst {
    typedef T Type;
};

template <typename T> struct AddConst<T, true> {
    typedef const T Type;
};

struct MyCopyPolicy {
    static const bool kIsCopyArgConst = true;
};

template <typename T, class CopyPolicy> struct Foo {

    // A helper struct to achieve "template typedef".
    template <typename T2> struct CopyArg {
        typedef typename AddConst<Foo<T2, CopyPolicy>,
            CopyPolicy::kIsCopyArgConst>::Type Type;
    };

    Foo() {}
    // Template copy constructor. Doesn't work.
    template <typename T2> Foo(typename CopyArg<T2>::Type& rhs) {}
};

int main() {
    Foo<int, MyCopyPolicy> foo1;
    Foo<double, MyCopyPolicy> foo2 = foo1;  // error!
}

1 个答案:

答案 0 :(得分:3)

也许这样的事可能适合你。我使用了C ++ 0x中的std :: enable_if。你可以很容易地使用boost,或者自己动手(它只是几行代码)。

#include <type_traits>

struct MyCopyPolicy {
    static const bool kIsCopyArgConst = true;
};

template <typename T, class CopyPolicy> struct Foo {

    // A helper struct to achieve "template typedef".
    template <typename T2> struct CopyArg {
        typedef CopyPolicy Type;
    };

    Foo() {}

    template <typename T2>
        Foo(const T2& rhs,
                typename std::enable_if<CopyArg<T2>::Type::kIsCopyArgConst>::type* = 0)
            {}
    template <typename T2>
        Foo(T2& rhs,
               typename std::enable_if<!CopyArg<T2>::Type::kIsCopyArgConst>::type* = 0)
            {}
};

int main() {
    Foo<int, MyCopyPolicy> foo1;
    Foo<double, MyCopyPolicy> foo2 = foo1;  // ok!
}

我不肯定这是最佳的。这只是从臀部射击,其中一个目标是距离你前进的最小距离。也许这就是你想去的地方,或者这可能会让你开始朝着正确的方向前进。

相关问题