相关疑难解决方法(0)

未作为最后一个参数传递时的模板参数包扣除

请考虑以下代码:

#include <iostream>
#include <functional>

template<typename... Args>
void testfunc(const std::function<void (float, Args..., char)>& func)
{

}

int main(int argc, char* argv[])
{
    auto func = [](float, int, char) {};
    auto sfunc = static_cast<std::function<void (float, int, char)>>(func);
    testfunc<int>(sfunc);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我明确指定了类型,因为(/sf/answers/2833325841/):

当参数包没有出现在参数声明的最后时,它是一个非推导的上下文.非推断的上下文意味着必须明确给出模板参数.

MSVC成功编译它,而gcc和clang都拒绝代码:

source_file.cpp: In function ‘int main(int, char**)’:
source_file.cpp:14:24: error: no matching function for call to ‘testfunc(std::function<void(float, int, char)>&)’
     testfunc<int>(sfunc);
                        ^
source_file.cpp:5:6: note: candidate: template<class ... Args> void testfunc(const std::function<void(float, Args ..., char)>&)
 void testfunc(const std::function<void (float, …
Run Code Online (Sandbox Code Playgroud)

c++ templates variadic-templates c++11

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

可变参数函数中可变参数模板类的隐式转换

考虑以下代码

#include <functional>
template<class ResultType, class ... Args>
void Foo( std::function<ResultType(Args...)> ) {}

void Dummy(int) {}

int main()
{
     Foo<void, int> ( std::function<void(int)>( Dummy ) ); // OK, no deduction and no conversion
     Foo( std::function<void(int)>( Dummy ) ); // OK, template argument deduction
     Foo<void, int>( Dummy ); // Compile error
}
Run Code Online (Sandbox Code Playgroud)

在第三个中,我知道不能进行模板推导,这就是明确指定模板参数的原因。但是为什么没有从void (*)(int)to的显式转换std::function<void(int)>

我查找了答案,但这些是关于模棱两可的重载解决方案或模板推论,而不是相关主题。

std::function 的模板参数(签名)不是其类型的一部分吗?

使用 std::function 进行模板类型推导

使用 std::function 进行隐式转换

然后我尝试使用我自己的模板类而不是 std::function 进行测试。

// Variadic template class
template<class ... T>
class Bar
{ …
Run Code Online (Sandbox Code Playgroud)

c++ templates variadic-functions implicit-conversion variadic-templates

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

模板推导因参数包后的参数而失败

我有这个功能:

template <typename... Args>
void f(Args... args, int last)
{
}
Run Code Online (Sandbox Code Playgroud)

如果我在没有显式模板参数的情况下调用它,模板推导会失

f(2, 2); // candidate expects 1 argument, 2 provided
Run Code Online (Sandbox Code Playgroud)

但是为参数包提供显式模板参数有效:

f<int>(2, 2); // compiles fine
Run Code Online (Sandbox Code Playgroud)

尽管从逻辑上讲,编译器应该能够推断出参数包除了最后一个参数类型之外的所有参数类型.我该如何解决这个问题?

c++ templates c++11 template-argument-deduction

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