【问题标题】:error: template parameter redeclared here as 'false'. some template magic错误:模板参数在此处重新声明为“假”。一些模板魔法
【发布时间】:2013-10-20 16:58:11
【问题描述】:

我尝试在 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 模板参数重载结构?

【问题讨论】:

  • 您不能在模板参数上“重载”模板。此外,您的专业化毫无意义,您可以只做static const bool second = Cond 而不必专业化。
  • 是的,这是真的。这可以在没有专门化的情况下完成,但我仍然想知道,为什么我不能重载模板来为类型和整数值提供不同的实例

标签: c++ templates metaprogramming template-specialization


【解决方案1】:

这样的东西能满足你的需要吗?

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2017-04-03
    相关资源
    最近更新 更多