gpt4 book ai didi

c++ - 当特征相同时,如何在为引用和非引用类型编写特征时减少重复

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:26:19 25 4
gpt4 key购买 nike

我有例子

#include <iostream>

template <typename T>
struct Base {};

template <>
struct Base<std::string> {
static const int value = true;
};

template <>
struct Base<std::string &> {
static const int value = true;
};

int main() {
bool a = Base<std::string>::value;
bool b = Base<std::string &>::value;

std::cout << a << b << std::endl;
}

https://godbolt.org/z/0NpYxB

请注意,我有两个相同的专业,想将其缩减为一个。我知道有两种解决方案,但我不想这样做。

(1) 删除调用点的引用,这样只需要一个特化。

(2) 创建一个基类并从中继承referenceno reference 版本。

是否有第三种选择,其中特化是引用和非引用类型的泛型?

需要 C++11 解决方案。

最佳答案

1) 看起来不错:

template <typename T>
struct BaseImpl {};

template <>
struct BaseImpl<std::string> {
static const int value = true;
};

template <typename T>
using Base = BaseImpl<typename std::remove_reference<T>::type>;

2) 看起来更冗长

template <typename T>
struct BaseImpl {};

template <>
struct BaseImpl<std::string> {
static const int value = true;
};

template <typename T>
struct Base : BaseImpl<T> {}; // or directly BaseImpl<std::remove_reference_t<T>>

template <typename T>
struct Base<T&> : BaseImpl<T> {};

3) 类似于 2),不那么冗长,但可能更棘手

template <typename T>
struct Base : Base<T&> {};

template <typename T>
struct Base<T&> {};

template <>
struct Base : Base<std::string> {
static const int value = true;
};

1) 似乎更具可读性,易于实现。

关于c++ - 当特征相同时,如何在为引用和非引用类型编写特征时减少重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55952756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com