【问题标题】:static function in template struct not using default template argument模板结构中的静态函数不使用默认模板参数
【发布时间】:2020-10-11 13:26:47
【问题描述】:

我有这段代码我无法编译,我想知道是否有办法解决它。错误是 - 类模板“a”的参数列表丢失。

//not compiling one
template <typename T = int>
struct a {
    static T x;
    static T function(T number) {
        return x = number;
    }
};

template <typename T>
T a<T>::x;

int main() {
    int b = a::function(5);
    return 0;
}

.

//compiling one
template <typename T = int>
struct a {
    static T x;
    static T function(T number) {
        return x = number;
    }
};

template <typename T>
T a<T>::x;

int main() {
    int b = a<int>::function(5);
    return 0;
}

为什么它不能使用我们默认传递的模板参数,我们如何在不输入模板参数的情况下解决这个问题?

【问题讨论】:

  • 错误是什么?请在问题中包含它
  • 问题不清楚。您正在寻找解决方法吗?你想达到什么目标?为什么工作代码不正常?
  • 需要默认使用int,但仍然可以选择使用a::function()将其更改为其他类型,但默认使用a::function()只需传递 a::function()

标签: c++ templates struct


【解决方案1】:

默认模板参数int可以不用指定,只需要指定a是模板即可:

int b = a<>::function(5);
      // ^^

【讨论】:

  • 有没有办法不用一个,只有一个?
  • @pesuww 不确定。你有什么特别的原因想要这样做,或者只是好奇?
  • 我想需要给它起一个别名using a = _a&lt;&gt;
  • 是的,我需要它用于我的另一个相当大的课程,所以我想小规模制作。
【解决方案2】:

有没有办法不用a&lt;&gt;,只用a

如果您的类模板 a 仅用于提供实用程序静态函数而不充当对象(带状态),您可以通过函数模板使用委托,该模板返回(虚拟)a 对象,其次是使用给定类型的对象,比如A,可以调用非静态和静态成员函数这一事实。

namespace detail {

template <typename T = int>
struct AImpl {
    static T x;
    static T function(T number) {
        return x = number;
    }
};

template <typename T>
T AImpl<T>::x;

}  // namespace detail

template<typename T = int>
constexpr detail::AImpl<T> a() { return {}; }

int main() {
    const auto b_int = a().function(5);
    const auto b_char = a<char>().function('a');
    (void)b_int; (void)b_char;
}

如果您实际上总是想使用推导并且从未实际指定类型模板参数的类型(当不是int 时),您可以通过单个函数模板交换类模板及其静态数据成员和成员函数包装一个具有静态存储持续时间的变量:

#include <type_traits>

template<typename T>
T function(T number) {
    static T x;
    return x = number;
}

int main() {
    const auto b_int = function(5);
    const auto b_char = function('a');
    static_assert(std::is_same_v<decltype(b_int), const int>, "");
    static_assert(std::is_same_v<decltype(b_char), const char>, "");
    (void)b_int; (void)b_char;
}

然而,这将是一个完全不同(并且更隐含)的 API。

【讨论】:

    猜你喜欢
    • 2011-06-11
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2016-03-01
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    相关资源
    最近更新 更多