c++ - 使用特殊化可变参数模板

标签 c++ templates return-type arithmetic-expressions

晚上好,

我在专门化可变参数模板时遇到问题。我需要以下模板:

template<typename... Ts>
using OPT = decltype(operator+(std::declval<Ts>()...))(Ts...);

问题是,当我尝试使用时,这无法编译

OTP<double,double>

所以我尝试通过它进行特化

template<>
using OPT<double,double> = double;

但现在我收到错误

error: expected unqualified-id before ‘using’
using OPT<double,double> = double;

有谁知道解决这个问题的方法还是我做错了什么?

感谢您的阅读和帮助!

最佳答案

您需要一个幕后的结构来实现这一点,因为别名模板无法专门化,也无法引用自身。

#include <utility>

template<typename T, typename... Ts>
struct sum_type {
    using type = decltype(std::declval<T>() + std::declval<typename sum_type<Ts...>::type>());
};

template <typename T>
struct sum_type<T> {
    using type = T;
};

template<typename... Ts>
using OPT = typename sum_type<Ts...>::type;

Demo.

关于c++ - 使用特殊化可变参数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39396516/

相关文章:

c++ - "array"是 c++11 标准下的关键字吗?

c++ - GCC 和 MS 编译器的模板实例化细节

c++ - 为什么 enable_if 的行为不如预期?

javascript - 为什么 regex.exec() 返回类型是 bool 值?

PHP 类方法返回类型

c++ - 将二维数组作为参数传递

c++ - 这是定义的行为吗?将数据存储为字符数组

c++ - 当我初始化一个大小为变量的数组时会发生什么?

c++ - 模板表达式和 visual studio 2005 c++

linux - 为什么 open(linux) 的返回值必须是 int 而不是 short?