标签: generic-programming

如何使用可变参数模板打印出函数的参数?

这个例子使用了一个通用的可变参数模板和函数。我想打印出传递给的参数f

#include <iostream>

template <typename T>
void print(T t) 
{
    std::cout << t << std::endl;
}

template <typename...T>
void f(T &&...args) 
{
    print(args...);
    f(args...);
}

int main() 
{
    f(2, 1, 4, 3, 5);
}
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

Compilation finished with errors:<br>
source.cpp: In instantiation of '`void f(T ...)` [with `T = {int, int, int, int, int}`]':<br>
source.cpp:16:20: required from here <br>
source.cpp:10:4: error: no matching function for call to '`print(int&, int&, int&, int&, int&)`'<br>
source.cpp:10:4: note: candidate is:<br>
source.cpp:4:6: note: …
Run Code Online (Sandbox Code Playgroud)

c++ templates generic-programming function-templates variadic-templates

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

具有泛型重载的 GetMethod

我有一个有两个方法的类,重载了相同的名称和参数,但一个是通用的:

public class Foo
{
    public string Bar(string s) { throw new NotImplementedException(); }
    public T Bar<T>(string s) { throw new NotImplementedException(); }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能获得MethodInfo这些方法之一?

例如:

var fooType = typeof(Foo);
var methodInfo = fooType.GetMethod("Bar", new[] { typeof(string) }); // <-- [System.Reflection.AmbiguousMatchException: Ambiguous match found.]
Run Code Online (Sandbox Code Playgroud)

.NET 小提琴在这里

.net c# generics reflection generic-programming

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

处理 f64 或 Complex64 返回类型。泛型?任何一个?

我有一个正常运行的 Rust 程序,使用实双精度数 ( f64) 作为基础类型,并希望扩展系统,以便它也可以处理复杂值 ( num::complex::Complex64)。

一个(简化示例)函数采用一些配置 struct config,并根据该输入在索引处生成一个潜在值idx

fn potential(config: &Config, idx: &Index3) -> Result<f64, Error> {
    let num = &config.grid.size;
    match config.potential {
        PotentialType::NoPotential => Ok(0.0),
        PotentialType::Cube => {
            if (idx.x > num.x / 4 && idx.x <= 3 * num.x / 4) &&
               (idx.y > num.y / 4 && idx.y <= 3 * num.y / 4) &&
               (idx.z > num.z / 4 && idx.z <= 3 * num.z / 4) …
Run Code Online (Sandbox Code Playgroud)

generic-programming either rust

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

在通用C++代码中移动基于范围的循环?

想象一下,你有这个通用的伪代码:

template<typename Iterable>
void f(Iterable&& iterable)
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

我们想要处理对可迭代对象1的 rvalue和lvalue引用,并且想法是该函数处理容器逐元素地执行操作.

我们想要将容器的参考规范转发给元素是合理的.换句话说,如果iterable是右值引用,则该函数必须从容器中移动元素.

使用C++ 17,我会这样做

auto [begin, end] = [&] {
    if constexpr(std::is_lvalue_reference_v<Iterable>)
        return std::array{std::begin(iterable),
                          std::end(iterable)};
    else
        return std::array{
            std::make_move_iterator(std::begin(iterable)),
            std::make_move_iterator(std::end(iterable))};
}();
std::for_each(begin, end, [&](auto&& element)
{
    ...
});
Run Code Online (Sandbox Code Playgroud)

显然,这不是维护2的最佳代码,容易出错,并且编译器可能不那么容易优化.

我的问题是:对于未来的C++标准,有可能引入转发基于范围的循环的概念吗?如果这样会好的

for(auto&& el : std::move(iterable))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

可以处理el作为右值参考.通过这种方式,这将是可能的:

template<typename Iterable>
void f(Iterable&& iterable)
{
    for(auto&& el : std::forward<Iterable>(iterable))
    {
        /*
         *  el is forwarded as lvalue reference if Iterable …
Run Code Online (Sandbox Code Playgroud)

c++ for-loop generic-programming c++17 c++20

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

在 C++ STL 中省略更大模板的类型参数

这是我在一本书上看到的一行代码

priority_queue<IteratorCurrentAndEnd, vector<IteratorCurrentAndEnd>, greater<>> min_heap;
Run Code Online (Sandbox Code Playgroud)

其中IteratorCurrentAndEnd是实现方法的类operator>。为什么我们可以用greater<>来代替greater<IteratorCurrentAndEnd>?我检查并读到了这样的东西,

template< class T = void >
struct greater;
Run Code Online (Sandbox Code Playgroud)

但我实在不知道这意味着什么。和类型有关系吗void?它到底是什么?

谢谢。

c++ stl generic-programming function-object c++11

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

从返回类型推断类型T的模板

我有一个模板如下:

template <class T>
vector<T> read_vector(int day)
{
  vector<T> the_vector;
  {...}
  return the_vector;
}
Run Code Online (Sandbox Code Playgroud)

我希望能够做类似的事情

vector<int> ints = read_vector(3);
vector<double> doubles = read_vector(4);
Run Code Online (Sandbox Code Playgroud)

C++模板是否有可能在调用它们时推断返回类型,或者我是否应该将伪参数传递给模板以及我想要的向量类型?后者有效,但更加混乱.

c++ templates generic-programming

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

赋值中的折叠表达式

我正在尝试使用折叠表达式来简化一些代码。在下面的代码中,我尝试将元素插入到数组中,但折叠表达式无法编译

struct test {
  std::string cmd[20];
  test() {
    int i = 0;
    auto insert = [&](auto... c) {
      assert(i < 20);
      (cmd[i++] = c), ...;
    };
    insert("c");
    insert("c", "c2");
  }
};
Run Code Online (Sandbox Code Playgroud)

编译器抱怨缺少“;”

c++ templates generic-programming fold-expression c++17

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

如何在 Swift 中使函数的返回类型通用

介绍

在我的应用程序中,我有一个名为“ElementData”的超类几个继承自它的子类。

每个子类都有自己的 validateModel() 方法,它返回不同的类型,具体取决于类——总是在一个数组中。

换句话说:该方法在每个子类中返回不同的类型。

例子

A类: func validateModel() -> [String]

B类: func validateModel() -> [Int]

C类: func validateModel() -> [MyCustomEnum]

如您所见,只有返回值彼此不同。

编辑:validateModel() 方法示例:

A类:

func validateModel() -> [DefaultElementFields]{ // DefaultElementFields is an enum with the different view types of my collection view

        var checkResult: [DefaultElementFields] = []

        if name == "" {
            checkResult.append(.Name)
        }

        if Int(rewardedPoints) == nil {
            checkResult.append(.Points)
        }

        if description == "" {
            checkResult.append(.Description)
        }

        if selectedImage == nil {
            checkResult.append(.Image) …
Run Code Online (Sandbox Code Playgroud)

arrays class generic-programming swift

2
推荐指数
2
解决办法
3551
查看次数

HList 的无形类型推断不起作用

我正在尝试实现用于获取第一个元素的通用函数:

import shapeless.ops.hlist.IsHCons
import shapeless.{Generic, HList}

object App {

  def main(args : Array[String]) {
    val a: Int = getFirst((1, 2, 3))
    val b: String = getFirst(("a", "b", 10, 45, "aaa"))
  }

  def getFirst[A, Head, Repr <: HList, Tail <: HList](input: A)
                                                     (implicit hcons: IsHCons.Aux[Repr, Head, Tail],
                                                      gen: Generic.Aux[A, Repr]): Head = gen.to(input).head
}
Run Code Online (Sandbox Code Playgroud)

问题是编译器无法正确推断Repr并将Tail它们设置为Nothing. 就这个:

Error:(9, 26) could not find implicit value for parameter gen: shapeless.Generic.Aux[(Int, Int, Int),Repr]
    val a: Int = getFirst((1, 2, …
Run Code Online (Sandbox Code Playgroud)

functional-programming scala generic-programming type-level-computation shapeless

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

我可以将作用域枚举用于带有模板的 C++ 标记调度吗?

模板新手在这里。我正在试验以下代码:

#include <type_traits>

enum class Thread
{
    MAIN, HELPER
};

template<typename T>
int f()
{
    static_assert(std::is_same_v<T, Thread::MAIN>);
    return 3;
}

int main()
{
    f<Thread::MAIN>();
}
Run Code Online (Sandbox Code Playgroud)

换句话说,如果函数不是从主线程调用的,我想提出一个编译时断言。显然,编译器不接受枚举器作为模板参数,大喊大叫invalid explicitly-specified argument for template parameter 'T'

我知道我可以使用两个结构作为标签:struct ThreadMainstruct ThreadHelper. 不幸的是,枚举 cass 已经在我的项目中随处使用,我宁愿避免重复。为此,我如何重用现有的枚举类?

c++ templates generic-programming

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