gpt4 book ai didi

c++ - 错误 : template parameter redeclared here as 'false' . 一些模板魔法

转载 作者:行者123 更新时间:2023-11-28 03:06:45 24 4
gpt4 key购买 nike

我尝试在 C++ 的元编程技术中实现有点智能的 Pair 类。我希望我的类可以包含不同的类型和常量。就像下面的代码:

template <typename F, typename S>
struct Pair {
typedef F first;
typedef S second;
};

template <typename F, bool Cond>
struct Pair {
typedef F first;
static const bool second = Cond;
};

但是这段代码在gcc 4.8.1上会导致编译错误

error: template parameter ‘class S’
template <typename F, typename S>
^
error: redeclared here as ‘bool Cond’

有什么方法可以通过 const 模板参数重载结构吗?

最佳答案

这样的东西能满足您的需求吗?

#include <type_traits>

template <typename F, typename S>
struct Pair {
typedef F first;
typedef S second;
};

template <typename F>
struct Pair<F, std::integral_constant<bool, true>> {
typedef F first;
static const bool second = false;
};

template <typename F>
struct Pair<F, std::integral_constant<bool, false>> {
typedef F first;
static const bool second = true;
};

Pair<int, std::true_type> t;
Pair<int, std::false_type> f;

或者更通用的方式:

template <typename F, typename T, T Val>
struct Pair<F, std::integral_constant<T, Val>> {
typedef F first;
static const T second = Val;
};

Pair<int, std::integral_constant<int,42>> p;

关于c++ - 错误 : template parameter redeclared here as 'false' . 一些模板魔法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19480189/

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