简体   繁体   中英

Achieve template only on const qualifier in C++

I want to get two classes that differ only on the constness of a parameter.

What I currently do is:
(This is a dummy minimal example.)

template <typename T>
struct Wrapper {
    Wrapper(T & t):
        t(t) {
    }

    T & t;
};

class Foo;

using Foo_wrapper = Wrapper<Foo>;
using Const_Foo_wrapper = Wrapper<const Foo>;

I would like my template to be declared exclusively on Foo, and to differ only on the const qualifier .
That would something such as:
(This is invalid syntax, to try to give the idea.)

class Foo;

template <qualifier Q>
struct Foo_base_wrapper {
    Wrapper(Q Foo & t):
        t(t) {
    }

    Q Foo & t;
};

using Foo_wrapper = Foo_base_wrapper<none>;
using Const_Foo_wrapper = Foo_base_wrapper<const>;

Is there a way to achieve this?

(A near solution may be with concepts, but that would be still more generic and complex, and I don't have C++ 20.)

You cannot use the const keyword alone but you can use template (partial) specialization to control the constness of a type with something like this.

enum Qualifier { Mutable, Const };

template<typename T, Qualifier Q>
struct Qualified
{
    using type = T;
};

template<typename T>
struct Qualified<T, Const>
{
    using type = const T;
};

template <Qualifier Q = Mutable>
struct Foo_base_wrapper
{
    using QualifiedFoo = typename Qualified<Foo, Q>::type;

    Foo_base_wrapper(QualifiedFoo & t) : t(t)
    { }

    QualifiedFoo & t;
};

using Foo_wrapper = Foo_base_wrapper<>;  // or explicitly Foo_base_wrapper<Mutable>
using Const_Foo_wrapper = Foo_base_wrapper<Const>;

If you don't have to define other wrappers, you can of course use directly Foo in the Qualified template and its specialization.

You may also be interested in the functions std::ref / std::cref to deal with the constness of references.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM