仅在C ++中的const限定符上实现模板

问题描述 投票:0回答:1

我想得到两个仅在参数的恒定性上不同的类。

我目前正在做的是:(这是一个虚拟的最小示例。)

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>;

我希望我的template仅在Foo上声明,并且仅在const限定符上声明。那将是这样的:((这是无效的语法,试图说明问题。)

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>;

有没有办法做到这一点?

(一个接近的解决方案可能是关于概念的,但这将更加通用和复杂,并且我没有C ++ 20。)

c++ templates const
1个回答
0
投票

您不能单独使用const关键字,但可以使用模板(部分)特殊化来控制类型的常量,例如:

© www.soinside.com 2019 - 2024. All rights reserved.