相关疑难解决方法(0)

为使用数组,向量,结构等传递给variadic函数或可变参数模板函数的所有参数指定一种类型?

我正在创建一个函数(可能是成员函数,而不是它很重要......也许它确实?)需要接受未知数量的参数,但我希望它们都是相同的类型.我知道我可以传入数组或向量,但我希望能够直接接受args列表而无需额外的结构甚至是额外的括号.看起来variadic函数本身并不是类型安全的,我不知道如何使用这个w/variadic模板函数.这基本上就是我的目标(更可能不是正确的代码,完全不是为了获取龙的列表,哈哈):

//typedef for dragon_list_t up here somewhere.

enum Maiden {
    Eunice
    , Beatrice
    , Una_Brow
    , Helga
    , Aida
};

dragon_list_t make_dragon_list(Maiden...) {
    //here be dragons
}
Run Code Online (Sandbox Code Playgroud)

要么

template<Maiden... Maidens> dragon_list_t make_dragon_list(Maidens...) {
    //here be dragons
}
Run Code Online (Sandbox Code Playgroud)

用法

dragon_list_t dragons_to_slay
    = make_dragon_list(Maiden.Eunice, Maiden.Helga, Maiden.Aida)
;
Run Code Online (Sandbox Code Playgroud)

尝试了类似于上面的一些事情,没有骰子.建议?我可能做出明显的疏忽?我知道这样做可能不是一件大事:

dragon_list_t make_dragon_list(std::array<Maiden> maidens) {
    //here be dragons.
}
dragon_list_t dragons_to_slay
    = make_dragon_list({Maiden.Eunice, Maiden.Helga, Maiden.Aida})
;
Run Code Online (Sandbox Code Playgroud)

但如果可能的话,我宁愿能够以第一种方式做到这一点.

c++ parameters templates variadic-functions c++11

40
推荐指数
7
解决办法
2万
查看次数

我们可以使用参数包作为 std::vector 初始值设定项吗?

我正在试验 C++11(到目前为止我已经使用了旧的 C++)并且我编写了以下代码:

#include <iostream>
#include <vector>
#include <type_traits>

using namespace std;

constexpr bool all_true(){
    return true;
}

template <typename Head, typename... Tail>
constexpr bool all_true(Head head, Tail... tail){
    static_assert( is_convertible<bool, Head>::value, "all_true arguments must be convertible to bool!");
    return static_cast<bool>(head) && all_true(tail...);
}

template<typename T, typename... Args>
void print_as(Args... args){
    static_assert( all_true(is_convertible<T,Args>::value...), "all arguments must be convertible to the specified type!");
    vector<T> v {static_cast<T>(args)...};
    for(T i : v) cout << i << endl;
}

int main(){
    print_as<bool>(1, 2, 0, …
Run Code Online (Sandbox Code Playgroud)

stdvector variadic-templates c++11

5
推荐指数
1
解决办法
1066
查看次数

处理“std::size_t”类型的可变参数函数参数

我正在尝试掌握可变函数/模板参数的窍门。但是,在下面的两个函数中,我很困惑为什么SumIndices不能编译(我收到编译器错误“expansion pattern \xe2\x80\x98std::size_t\xe2\x80\x99 {aka \xe2\x80\x98long unsigned int\xe2\x80\x99} 不包含参数包”)而包含SumValues

\n
template <typename ...t_data_type>\nconstexpr auto SumValues(t_data_type ..._values) { \n  return (_values + ...); \n}\n\nconstexpr auto SumIndices(std::size_t ..._indices) { \n  return (_indices + ...); \n}\n
Run Code Online (Sandbox Code Playgroud)\n

如果有人能为我澄清这个困惑,我将不胜感激!

\n

c++ variadic-functions variadic-templates c++17 c++20

1
推荐指数
1
解决办法
514
查看次数